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 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短