替换字符数组中的字符或子字符串的标准函数? [英] Standard function to replace character or substring in a char array?

查看:37
本文介绍了替换字符数组中的字符或子字符串的标准函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

没有直接的函数可以做到这一点.你必须写这样的东西,使用 strchr:

There is no direct function to do that. You have to write something like this, using 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

这篇关于替换字符数组中的字符或子字符串的标准函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆