Cプログラミング
 Computer >> コンピューター >  >> プログラミング >> Cプログラミング

文字列内の文字のすべての出現を置き換える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("\n 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("\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

  1. 文字列内の「a」のすべての出現箇所を$に置き換えるPythonプログラム

    文字列内で出現するすべての「a」を「$」などの文字に置き換える必要がある場合は、文字列を繰り返して、「+=」演算子を使用して置き換えることができます。 以下は同じのデモンストレーションです- 例 my_str = "Jane Will Rob Harry Fanch Dave Nancy" changed_str = '' for char in range(0, len(my_str)):    if(my_str[char] == 'a'):       changed_str +=

  2. 指定された文字列内の各文字の出現を検索するPythonプログラム

    この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −文字列が与えられたので、与えられた文字列内の各文字の出現を見つける必要があります。 ここでは、以下で説明する3つのアプローチについて説明します。L アプローチ1-ブルートフォースアプローチ 例 test_str = "Tutorialspoint" #count dictionary count_dict = {} for i in test_str:    #for existing characters in the dictionary   &nbs