我需要标准库中的一个函数,用一个字符替换字符串中所有出现的字符.
我还需要标准库中的一个函数,它用字符串替换字符串中所有出现的子字符串.
标准库中是否有这样的功能?
Sup*_*kus 14
这没有直接的功能.你必须写这样的东西,使用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;
}
Run Code Online (Sandbox Code Playgroud)
对于整个字符串,我指的是这个已回答的问题
Ser*_*sta 10
标准库中没有这样的函数。
您可以轻松地滚动自己的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;
}
Run Code Online (Sandbox Code Playgroud)
这个返回被替换的字符数,甚至对自己替换字符免疫