런타임에 문자열을 입력하고 콘솔에서 대체할 문자를 읽습니다. 그런 다음 마지막으로 문자열 내부에서 발생하는 이전 문자 자리에 배치되어야 하는 새 문자를 읽습니다.
프로그램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