用 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

更新於: 24-04-2021

6K+ 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告