指定された文字列を置換するためのC言語の方法は何ですか?

C言語では、特定の文字列を置き換える方法は通常、以下のいくつかがあります:

  1. strreplace()関数
  2. strreplace()関数
#include <stdio.h>
#include <string.h>

void strreplace(char *str, const char *old, const char *new) {
    char *pos, temp[1000];
    int index = 0;
    int old_len = strlen(old);
    
    while ((pos = strstr(str, old)) != NULL) {
        strcpy(temp, str);
        index = pos - str;
        str[index] = '\0';
        strcat(str, new);
        strcat(str, temp + index + old_len);
    }
}

int main() {
    char str[1000] = "Hello, World! This is a test.";
    char old_str[] = "test";
    char new_str[] = "example";
    
    printf("Before replace: %s\n", str);
    strreplace(str, old_str, new_str);
    printf("After replace: %s\n", str);
    
    return 0;
}

結果は次の通りです:

Before replace: Hello, World! This is a test.
After replace: Hello, World! This is a example.
  1. 文字列をループや文字配列を使うことで、文字列を一文字ずつ比較して置換することができます。以下に例示したコードを参考にしてください。
#include <stdio.h>
#include <string.h>

void strreplace(char *str, const char *old, const char *new) {
    int i, j, k;
    int str_len = strlen(str);
    int old_len = strlen(old);
    int new_len = strlen(new);
    
    for (i = 0; i <= str_len - old_len; i++) {
        if (strncmp(str + i, old, old_len) == 0) {
            for (j = i, k = 0; k < new_len; j++, k++) {
                str[j] = new[k];
            }
            i += new_len - 1;
        }
    }
}

int main() {
    char str[1000] = "Hello, World! This is a test.";
    char old_str[] = "test";
    char new_str[] = "example";
    
    printf("Before replace: %s\n", str);
    strreplace(str, old_str, new_str);
    printf("After replace: %s\n", str);
    
    return 0;
}

出力結果は前述の方法と同じです。

これらの方法はすべて文字列の置換を実現できますが、どの方法を選択するかは、具体的な要件とプログラミングスタイルに依存します。

bannerAds