Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C แทนที่คำในข้อความด้วยคำอื่นที่กำหนด

ในโปรแกรมนี้ เราได้รับสามสตริงคือ txt, oldword, newword งานคือสร้างโปรแกรม C เพื่อแทนที่คำในข้อความด้วยคำอื่นที่กำหนด

โปรแกรมจะค้นหาทุกครั้งที่ oldword ปรากฏในข้อความและแทนที่ด้วย newword

ตัวอย่างเพื่อเข้าใจปัญหา

อินพุต

text = "I am learning programming"
oldword = "learning"
newword = "practicing"

เอาต์พุต

"I am practicing programming"

เพื่อแก้ปัญหานี้ เราจะหาจำนวนครั้งที่ oldword ปรากฏในสตริงก่อน แล้วสร้างสตริงใหม่ที่จะจัดเก็บข้อความที่แทนที่คำแล้ว

โปรแกรม C แทนที่คำในข้อความด้วยคำอื่นที่กำหนด

// โปรแกรม C แทนที่คำในข้อความด้วยคำอื่นที่กำหนด

ตัวอย่างโค้ด

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void replaceWordInText(const char *text, const char *oldWord, const char *newWord) {
    int i = 0, cnt = 0;
    int len1 = strlen(newWord);
    int len2 = strlen(oldWord);
    for (i = 0; text[i] != '\0'; i++) {
        if (strstr(&text[i], oldWord) == &text[i]) {
            cnt++;
            i += len2 - 1;
        }
    }
    char *newString = (char *)malloc(i + cnt * (len1 - len2) + 1);
    i = 0;
    while (*text) {
        if (strstr(text, oldWord) == text) {
            strcpy(&newString[i], newWord);
            i += len1;
            text += len2;
        } else {
            newString[i++] = *text++;
        }
    }
    printf("สตริงใหม่: %s\n", newString);
}

int main() {
    char str[] = "I am learning programming";
    char c[] = "learning";
    char d[] = "practicing";
    char *result = NULL;
    printf("สตริงต้นฉบับ: %s\n", str);
    replaceWordInText(str, c, d);
    return 0;
}

ผลลัพธ์

สตริงต้นฉบับ: I am learning programming
สตริงใหม่: I am practicing programming