C 언어로 string Replace 함수 만들기 2 번 째 방법이다.
/*
https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word/
*/
// C program to search and replace
// all occurrences of a word with
// other word.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to replace a string with another
// string
char* replaceWord(const char* s, const char* oldW,
const char* newW)
{
char* result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
// Counting the number of times old word
// occur in the string
for (i = 0; s[i] != '\0'; i++) {
if (strstr(&s[i], oldW) == &s[i]) {
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;
while (*s) {
// compare the substring with the result
if (strstr(s, oldW) == s) {
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}
result[i] = '\0';
return result;
}
// Driver Program
int main()
{
char str[] = "xxforxx xx for xx";
char c[] = "xx";
char d[] = "Geeks";
char* result = NULL;
// oldW string
printf("Old string: %s\n", str);
result = replaceWord(str, c, d);
printf("New String: %s\n", result);
free(result);
return 0;
}
'C 언어' 카테고리의 다른 글
| C언어에서 조건부 컴파일 하기 (0) | 2021.09.18 |
|---|---|
| C언어로 만든 Youtube 플레이리스트 추출 프로그램 (0) | 2021.09.12 |
| C언어로 만든 코드 들여쓰기 프로그램 (0) | 2021.09.01 |
| C 언어로 간단한 게임 만들기 (0) | 2021.08.16 |
| C 언어로 숫자 야구 게임 만들기 (0) | 2021.07.15 |
댓글