C-如何查找和更改字符串中的单个特定字符

C-如何查找和更改字符串中的单个特定字符,c,C,我正在尝试做一些只改变字符串中一个字符的事情。举个例子 char str[10]; fgets(str,10,stdin); //input hello // do something to change 'hello to he1lo' 我所能找到的只是一些函数可以更改所有相同的字母。您可以通过搜索字符串进行修改,然后将其替换为新字符 #include<stdio.h> int replace(char *str,const char old_char,const char n

我正在尝试做一些只改变字符串中一个字符的事情。举个例子

char str[10];
fgets(str,10,stdin); //input hello
// do something to change 'hello to he1lo'

我所能找到的只是一些函数可以更改所有相同的字母。

您可以通过搜索字符串进行修改,然后将其替换为新字符

#include<stdio.h>

int replace(char *str,const char old_char,const char new_char,const int replace_char_count) {

    int count_replaced_chars = 0;
    for(int i = 0; str[i] != '\0';i++) {
        if(str[i] == old_char) {
            str[i] = new_char;
            count_replaced_chars++;
            if(count_replaced_chars == replace_char_count)
                return 0;
        }
    }
    return -1;
}

int main()
{
    char str[10];
    char new_char = '1';
    char old_char = 'l';
    int replace_char_count = 0;

    printf("Enter the string in which chars to be replaced\n");
    fflush(stdout);
    fgets(str,10,stdin); //input hello

    printf("Enter how many chars to replaced\n");
    fflush(stdout);
    scanf("%d",&replace_char_count);


    if(!replace(str,old_char,new_char,replace_char_count))
        printf("Successfully %d number of replaced char\n",replace_char_count);
    else
        printf("char not found\n");

    printf("%s\n",str);

}
#包括
int replace(char*str、const char old\u char、const char new\u char、const int replace\u char\u count){
整数计数替换字符=0;
对于(int i=0;str[i]!='\0';i++){
if(str[i]==旧字符){
str[i]=新字符;
count_替换_chars++;
if(count\u replaced\u chars==replace\u char\u count)
返回0;
}
}
返回-1;
}
int main()
{
char-str[10];
char new_char='1';
char old_char='l';
int replace_char_count=0;
printf(“输入要替换字符的字符串\n”);
fflush(stdout);
fgets(str,10,stdin);//输入hello
printf(“输入要替换的字符数\n”);
fflush(stdout);
scanf(“%d”、&replace\u char\u count);
如果(!替换(str,旧字符,新字符,替换字符计数))
printf(“已成功替换%d个字符”,替换字符计数);
其他的
printf(“未找到字符\n”);
printf(“%s\n”,str);
}

您可以访问相应的索引,然后对其进行修改。在上面的示例中,您可以通过str[2]=“1”进行修改;是的,但它是基于用户的输入,程序不应该决定字符串。你可以搜索你想要替换的字母,替换它,然后退出函数。我知道,但如果你这样做,你将更改所有相同的字母,我只想更改一个。我下面的解决方案必须解决你的问题。我希望我正确地理解了你的问题:-)是的,就是这样,只是好奇如果输入是Hello怎么办?我怎么能让它成为he11lo?那么你能接受答案吗。用于修改多个(例如:2个)字母。在“替换”函数中,您可以计算已替换的字母数,并在计数为2时退出该函数。如果用户可以选择更改的次数,我会这样做。您可以从用户处获取他/她要修改的字母数的输入,并将该值作为参数传递给函数。您可以显示我应该修改的位置吗花5个小时搞乱一个代码。我的大脑要爆炸了:(