C程序替换字符串中所有出现的字符
在运行时输入字符串并在控制台读取要替换的字符。然后,最后读取一个新字符,该字符必须放置在旧字符的位置,它出现在字符串中。
程序1
以下是替换所有出现的字符的C程序-
#include输出结果#include int main(){ char string[100], ch1, ch2; int i; printf("输入一个字符串: "); gets(string); printf("输入要搜索的字符: "); scanf("%c", &ch1); getchar(); printf("输入一个字符来代替old: "); scanf("%c", &ch2); for(i = 0; i <= strlen(string); i++){ if(string[i] == ch1){ string[i] = ch2; } } printf("\n the string after replace of '%c' with '%c' = %s ", ch1, ch2, string); return 0; }
执行上述程序时,会产生以下结果-
enter a string: nhooo.com enter a character to search: i enter a char to replace in place of old: % the string after replace of 'i' with '%' = Tutor%als Po%nt enter a string: c programming enter a character to search: m enter a char to replace in place of old: $ the string after replace of 'm' with '$' = c progra$$ing
程序2
以下是第一次出现时要替换的C程序-
#include输出结果#include int main(){ char string[100], ch1, ch2; int i; printf("输入一个字符串: "); gets(string); printf("输入要搜索的字符: "); scanf("%c", &ch1); getchar(); printf("输入一个字符来代替old: "); scanf("%c", &ch2); for(i = 0; string[i]!='\0'; i++){ if(string[i] == ch1){ string[i] = ch2; break; } } printf("\n the string after replace of '%c' with '%c' = %s ", ch1, ch2, string); return 0; }
执行上述程序时,会产生以下结果-
Run 1: enter a string: Tutorial Point enter a character to search: o enter a char to replace in place of old: # the string after replace of 'o' with '#' = Tut#rial Point Run 2: enter a string: c programming enter a character to search: g enter a char to replace in place of old: @ the string after replace of 'g' with '@' = c pro@ramming
热门推荐
10 医生节蛋糕祝福语简短
11 18岁祝福语搞笑简短
12 新年的鸡汤祝福语简短
13 职场离职文案祝福语简短
14 农民朋友发财祝福语简短
15 简短长辈新年祝福语
16 国庆简短幽默祝福语
17 打牌翻盘祝福语简短
18 情人表白祝福语简短大气