我正在尝试制作仅更改字符串中一个字符的内容。例如。
char str[10];
fgets(str,10,stdin); //input hello
// do something to change 'hello to he1lo'
我所能找到的就是一些函数将所有相同的字母都改变了。
答案 0 :(得分:-2)
您可以通过搜索字符串进行修改,然后将其替换为新字符。
#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);
}