第一堂 C 编程课,开始学习编程。我们目前正在学习 C 中的数组,这是一项帮助理解数组的学习任务,并获得一个程序,该程序将创建一个随机的大写字母字符串,然后要求用户输入最多 20 个大写字母,然后将这些字母替换为以前用 *. 生成的随机字符串。我可以生成随机字符串,但是,我在理解将字符串传递给第二个函数以替换所选值的最佳方法时遇到了问题。
简要示例:
随机字符串:AOIHGGDGIYGDYFDYIGDGPIGD
输入要替换的字母(最多 20 个字母):GD
新字符串:AOIH****IYYF*YI***PI
下面是我目前的代码。非常感谢任何有关如何以及更改以下代码的哪一部分以实现此目的的建议!
当前部分错误的输出示例:
JOAUZKKMJVNDFABILLKAWNWEKUEJGHKRCBDUYYRG
输入要替换的字符:W
替换后修改后的字符串为:Θi。
AKNZPUWCCKNOIQADOYXZIVCGFUWTKRQOGSWSPFFS
输入要替换的字符:FSQ
替换后修改后的字符串为:Θi。
非常感谢您的时间和指导。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void getRandomStr();
void strreplace(char s1[], char chr, char repl_chr);
int main(int argc, const char argv[])
{
char s1[41], s2, repl_chr;
getRandomStr();
printf("%c\n");
gets(s1);
printf("\nEnter character to be replaced: ");
s2 = getchar();
fflush(stdin);
repl_chr = '*';
printf("\nModified string after replacement is: ");
strreplace(getRandomStr, s2, repl_chr);
getch();
return 0;
return 0;
}
void getRandomStr(){
char s1[41];
int i;
srand(time(NULL));
for (i = 0; i < 40; i++){
char c = rand() % 26 + 'A';
s1[i] = c;
}
for (i = 0; i < 40; i++){
putchar(s1[i]);
}
}
void strreplace(char s1[], char chr, char repl_chr)
{
int i = 0;
while (s1[i] != '\0')
{
if (s1[i] == chr)
{
s1[i] = repl_chr;
}
i++;
}
puts(s1);
return 0;
}
最佳答案
正如其他人在表扬中提到的,您的代码中的一些问题是:
- 不要在 getRandomStr() 中以 null 终止字符串
- 你只从用户那里获取一个字符而不是整个字符串(你想修改多个字符,而不仅仅是一个)
我已经修改你的功能如下:
void getRandomStr(char* s1);
void strreplace(char s1[], char chrs[], char repl_chr);
int main(int argc, const char * argv[]) {
char s1[41];
char s2[256], repl_chr;
getRandomStr(s1);
printf("%s\n", s1);
//gets(s1);
printf("\nEnter characters to be replaced: ");
fgets(s2, sizeof(s2), stdin);
repl_chr = '*';
printf("\nModified string after replacement is: ");
strreplace(s1, s2, repl_chr);
//getch();
return 0;
}
void getRandomStr(char* s1){
int i;
srand(time(NULL));
for (i = 0; i < 40; i++){
char c = rand() % 26 + 'A';
s1[i] = c;
}
s1[40] = '\0';
}
void strreplace(char s1[], char chrs[], char repl_chr)
{
int i = 0;
while (chrs[i] != '\0') {
for (int j = 0; s1[j] != '\0'; j++){
if (s1[j] == chrs[i])
{
s1[j] = repl_chr;
}
}
i++;
}
puts(s1);
}
关于C 程序生成随机大写字符串并替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242321/