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
첫 번째 실행에서는 문자열 "Tutorials Point"의 모든 'i'가 '%'로 교체되었고, 두 번째 실행에서는 "c programming"의 모든 'm'이 '$'로 바뀐 것을 확인할 수 있습니다.
프로그램 2: 첫 번째 문자만 교체하기
다음은 문자열에서 해당 문자가 처음 등장하는 위치 한 곳만 교체하는 C 프로그램입니다. 교체를 수행한 직후 break 문으로 반복문을 종료하기 때문에 이후에 등장하는 동일한 문자는 그대로 유지됩니다.
#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
"Tutorial Point"에는 'o'가 두 개 있지만, 첫 번째 'o'만 '#'으로 교체되고 두 번째 'o'는 그대로 남아 있는 점에 주목하세요.
참고 사항
예제에서 사용한 gets() 함수는 입력 길이를 제한할 수 없어 버퍼 오버플로우 위험이 크기 때문에 C11 표준에서 제거되었습니다. 실제 프로젝트에서는 fgets()와 같은 안전한 입력 함수를 사용하는 것이 좋습니다. 또한 두 scanf() 호출 사이에 위치한 getchar()는 이전 입력에서 남아 있는 개행 문자('\n')를 입력 버퍼에서 제거하여, 다음 문자 입력이 정상적으로 처리되도록 돕는 역할을 합니다.