c 语言字符串替换字符串,c – 用字符串替换字符串中的char

我想用字符串替换字符串中的字符.我可以就地做吗?由于新字符串的长度大于原始字符串.问题是我可以使用额外的缓冲区吗?

例如

void replaceChar(std::string &input, std::string replacementString, char charToReplace)

{

//some code here. No additional buffer

}

void main(){

std::string input = "I am posting a comment on LinkedIn";

std::string replacementString = "pppp";

char charToReplace = 'o';

replaceChar(input, replacementString, charToReplace);

}

我只想要策略(算法).如果算法的设计保持一定的语言,一旦它被启动就不会动态增加或减少字符串长度,这将是很好的

解决方法:

std :: string有一个替换成员,但它的工作方式是数字位置,而不是字符串的先前内容.因此,您通常必须在循环中将它与find成员组合,如下所示:

std::string old("o");

int pos;

while ((pos = x.find(old)) != std::string::npos)

x.replace(pos, old.length(), "pppp");

就个人而言,我很少关注字符串调整大小的频率,但如果这是一个主要问题,你可以使用std :: count来查找旧字符串的出现次数,乘以旧字符串之间的大小差异和新字符串,并使用std :: string :: reserve()来保留足够的空间.但请注意,在C 11中添加了保留 – 较旧的实现将不具备它.

编辑:虽然它不是你所使用的字符串的问题,正如@ipc所指出的,如果替换字符串包含要替换的值的实例,这将无法正常工作.如果您需要处理它,您需要在字符串中提供开始每次搜索的偏移量:

int pos = 0;

while ((pos = x.find(old, pos)) != std::string::npos) {

x.replace(pos, old.length(), rep);

pos += rep.length();

}

或者,在这种情况下,您可能更喜欢for循环:

std::string old("o");

std::string rep("pop");

for (int pos=0;

(pos = x.find(old, pos)) != std::string::npos;

pos+=rep.length())

{

x.replace(pos, old.length(), rep);

}

标签:c,string,algorithm

来源: https://codeday.me/bug/20190729/1573779.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值