Cho văn bản text, từ cũ oldWord, từ mới newWord. Thay thế tất cả oldWord trong text bằng newWord.
Ví dụ
Đầu vào - text="I am learning programming", oldWord="learning", newWord="practicing"
Đầu ra - "I am practicing programming"
Phương pháp
- Đếm số lần xuất hiện oldWord (dùng strstr)
- Cấp phát bộ nhớ cho chuỗi mới: len(text) + count*(len(new)-len(old)) + 1
- Duyệt text, nếu tìm thấy oldWord → copy newWord, nhảy qua oldWord
- Không thì copy ký tự hiện tại
Chương trình mẫu
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void replaceWord(const char* text, const char* oldWord, const char* newWord) {
int cnt = 0, len1 = strlen(newWord), len2 = strlen(oldWord);
// Đếm số lần xuất hiện
for (int i = 0; text[i]; i++) {
if (strstr(&text[i], oldWord) == &text[i]) {
cnt++;
i += len2 - 1;
}
}
// Cấp phát chuỗi mới
char* newStr = malloc(strlen(text) + cnt * (len1 - len2) + 1);
int i = 0;
while (*text) {
if (strstr(text, oldWord) == text) {
strcpy(&newStr[i], newWord);
i += len1;
text += len2;
} else {
newStr[i++] = *text++;
}
}
newStr[i] = '\0';
printf("Chuỗi mới: %s\n", newStr);
free(newStr);
}
int main() {
char str[] = "I am learning programming";
char oldW[] = "learning";
char newW[] = "practicing";
printf("Gốc: %s\n", str);
replaceWord(str, oldW, newW);
return 0;
}
Kết quả
Gốc: I am learning programming Chuỗi mới: I am practicing programming