C语言 替换字符数组中的字符或子字符串的标准函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32496497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:07:00  来源:igfitidea点击:

Standard function to replace character or substring in a char array?

cstringreplace

提问by MOHAMED

I need a function from the standard library that replaces all occurrences of a character in a string by another character.

我需要标准库中的一个函数,用另一个字符替换字符串中所有出现的字符。

I also need a function from the standard library that replaces all occurrences of a substring in a string by another string.

我还需要标准库中的一个函数,该函数将一个字符串中出现的所有子字符串替换为另一个字符串。

Are there any such functions in the standard library?

标准库中有没有这样的函数?

回答by Superlokkus

There is no direct function to do that. You have to write something like this, using strchr:

没有直接的功能可以做到这一点。你必须写这样的东西,使用strchr

char* replace_char(char* str, char find, char replace){
    char *current_pos = strchr(str,find);
    while (current_pos){
        *current_pos = replace;
        current_pos = strchr(current_pos,find);
    }
    return str;
}

For whole strings, I refer to this answered question

对于整个字符串,我参考了这个已回答的问题

回答by Serge Ballesta

There are not such functions in the standard libraries.

标准库中没有这样的函数。

You can easily roll your own using strchrfor replacing one single char, or strstrto replace a substring (the latter will be slightly more complex).

您可以轻松地使用自己来strchr替换单个字符或strstr替换子字符串(后者会稍微复杂一些)。

int replacechar(char *str, char orig, char rep) {
    char *ix = str;
    int n = 0;
    while((ix = strchr(ix, orig)) != NULL) {
        *ix++ = rep;
        n++;
    }
    return n;
}

This one returns the number of chars replaced and is even immune to replacing a char by itself

这个返回被替换的字符数,甚至对自己替换字符免疫