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

โปรแกรม C แทนที่ตัวอักษรในสตริง (Replace All / First Occurrence)


รับสตริงและตัวอักษรที่ต้องการแทนที่ แล้วระบุตัวอักษรใหม่ แล้วแทนที่ในสตริง

โปรแกรม 1: แทนที่ทุกครั้งที่พบ (Replace All)

#include <stdio.h>
#include <string.h>
int main() {
    char string[100], ch1, ch2;
    int i;
    
    printf("Enter a string: ");
    fgets(string, sizeof(string), stdin);
    string[strcspn(string, "\n")] = 0;  // ลบ newline
    
    printf("Enter character to search: ");
    scanf(" %c", &ch1);
    
    printf("Enter character to replace with: ");
    scanf(" %c", &ch2);
    
    for(i = 0; i <= strlen(string); i++) {
        if(string[i] == ch1) string[i] = ch2;
    }
    
    printf("\nString after replacing '%c' with '%c' = %s\n", 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: แทนที่เฉพาะครั้งแรกที่พบ (Replace First Occurrence)

#include <stdio.h>
#include <string.h>
int main() {
    char string[100], ch1, ch2;
    int i;
    
    printf("Enter a string: ");
    fgets(string, sizeof(string), stdin);
    string[strcspn(string, "\n")] = 0;
    
    printf("Enter character to search: ");
    scanf(" %c", &ch1);
    printf("Enter character to replace with: ");
    scanf(" %c", &ch2);
    
    for(i = 0; string[i] != '\0'; i++) {
        if(string[i] == ch1) {
            string[i] = ch2;
            break;  // หยุดหลังแทนที่ครั้งแรก
        }
    }
    
    printf("\nString after replacing '%c' with '%c' = %s\n", 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