用 C 语言程序替换字符串中的所有出现字符
在运行时输入一个字符串并从控制台中读取一个字符进行替换。最终,读取一个新字符,放置在字符串中旧字符出现的位置。
程序 1
以下是用 C 语言编写的替换所有出现字符的程序 -
#include <stdio.h> #include <string.h> int main(){ char string[100], ch1, ch2; int i; printf("enter a string : "); gets(string); printf("enter a character to search : "); scanf("%c", &ch1); getchar(); printf("enter a char to replace in place of old : "); scanf("%c", &ch2); for(i = 0; i <= strlen(string); i++){ if(string[i] == ch1){ string[i] = ch2; } } printf("
the string after replace of '%c' with '%c' = %s ", ch1, ch2, string); return 0; }
输出
执行以上程序时,它将产生以下结果 -
enter a string: Tutorials Point 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 <stdio.h> #include <string.h> int main(){ char string[100], ch1, ch2; int i; printf("enter a string : "); gets(string); printf("enter a character to search : "); scanf("%c", &ch1); getchar(); printf("enter a char to replace in place of old : "); scanf("%c", &ch2); for(i = 0; string[i]!='\0'; i++){ if(string[i] == ch1){ string[i] = ch2; break; } } printf("
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
广告