以下是两种实现方式:

方式一:使用标准库函数strtok、strcmp和strcpy实现字符串替换

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

void replace_str(char *str, const char *old_str, const char *new_str, int case_sensitive) {
    char *token, *str_ptr, *new_str_ptr, *temp_str;
    int old_len = strlen(old_str), new_len = strlen(new_str);
    temp_str = (char *)malloc(strlen(str) + 1);
    strcpy(temp_str, str);
    str_ptr = temp_str;

    while ((token = strtok(str_ptr, old_str)) != NULL) {
        str_ptr = NULL;
        if (case_sensitive ? strcmp(token, old_str) == 0 : strcasecmp(token, old_str) == 0) {
            new_str_ptr = (char *)malloc(strlen(token) + new_len + 1);
            strcpy(new_str_ptr, new_str);
            strcat(new_str_ptr, token + old_len);
            strcpy(token, new_str_ptr);
            free(new_str_ptr);
        }
    }
    strcpy(str, temp_str);
    free(temp_str);
}

int main() {
    char str[] = "Hello, World! This is a test string.";
    replace_str(str, "test", "example", 1);
    printf("%s\n", str);
    replace_str(str, "hello", "Hi", 0);
    printf("%s\n", str);
    return 0;
}

方式二:使用指针操作实现字符串替换

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

void replace_str(char *str, const char *old_str, const char *new_str, int case_sensitive) {
    char *str_ptr = str, *old_ptr, *new_ptr;
    int old_len = strlen(old_str), new_len = strlen(new_str);

    while (*str_ptr != '\0') {
        old_ptr = (char *)old_str;
        new_ptr = (char *)new_str;
        while (*str_ptr != '\0' && (case_sensitive ? *str_ptr == *old_ptr : tolower(*str_ptr) == tolower(*old_ptr))) {
            str_ptr++;
            old_ptr++;
        }
        if (*old_ptr == '\0') {
            char *temp_ptr = str_ptr - old_len;
            char *temp_str = (char *)malloc(strlen(str_ptr) + 1);
            strcpy(temp_str, str_ptr);
            *temp_ptr = '\0';
            strcat(str, new_str);
            strcat(str, temp_str + old_len);
            free(temp_str);
            str_ptr = temp_ptr + new_len;
        } else {
            str_ptr++;
        }
    }
}

int main() {
    char str[] = "Hello, World! This is a test string.";
    replace_str(str, "test", "example", 1);
    printf("%s\n", str);
    replace_str(str, "hello", "Hi", 0);
    printf("%s\n", str);
    return 0;
}
``

原文地址: http://www.cveoy.top/t/topic/fmnb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录