C言語で文字列中の特定の文字を置き換える方法は何ですか?

C言語では、文字列中の特定の文字を置き換えるためにループや条件分岐を使用することができます。以下は一つの例です:

#include <stdio.h>

void replaceChar(char *str, char oldChar, char newChar) {
    int i = 0;
    while (str[i] != '\0') {
        if (str[i] == oldChar) {
            str[i] = newChar;
        }
        i++;
    }
}

int main() {
    char str[] = "Hello, World!";
    char oldChar = 'o';
    char newChar = 'x';

    printf("原始字符串: %s\n", str);
    replaceChar(str, oldChar, newChar);
    printf("替换后字符串: %s\n", str);

    return 0;
}

実行結果は:

原始字符串: Hello, World!
替换后字符串: Hellx, Wxrld!

上記の例では、replaceChar関数は、文字列を指すポインタ、置き換える必要のある文字oldChar、および置き換え後の文字newCharを受け入れます。文字列内の各文字をループして、現在の文字がoldCharと等しい場合は、newCharに置き換えます。

bannerAds