用一些字符串替换字符串中的char [英] Replace char in string with some string inplace

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

问题描述


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


i want to replace a character in the string with a string. can i do it in-place? As the new string has length greater than original string.Question is that can i do with using additional buffer? for example

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);
}

我只想要策略(算法)。如果设计算法时要记住某种语言,那会很好,一旦像c ++这样初始化字符串,该语言就不会动态地增加或减少字符串长度。

I only want the strategy (algorithm). it would be good if algorithm will be designed keeping some language in mind that will not dynamically increase or decrease the string length once it was initilized like c++

推荐答案

std :: string 具有 replace 成员,但它在数字位置方面有效,而不是比字符串的先前内容。因此,通常必须将其与 find 成员组合成一个循环,如下所示:

std::string has a replace member, but it works in terms of numerical positions, rather than the previous content of the string. As such, you normally have to combine it with the find member in a loop, something like this:

std::string old("o");

int pos;

while ((pos = x.find(old)) != std::string::npos)
    x.replace(pos, old.length(), "pppp");

就个人而言,我很少担心字符串调整大小的频率,但是如果它是主要的您可以使用 std :: count 来查找 old 字符串出现的次数,然后乘以差值大小介于新旧字符串之间,并使用 std :: string :: reserve()保留足够的空间。但是请注意,在C ++ 11中添加了 reserve -较早的实现则没有。

Personally, I'd rarely get concerned about how often the string gets resized, but if it's a major concern, you can use std::count to find the number of occurrences of the old string, multiply by the difference in size between the old and new strings, and use std::string::reserve() to reserve enough space. Note, however, that reserve was added in C++11 -- older implementations won't have it.

编辑:尽管与您使用的字符串无关,正如@ipc指出的那样,如果替换字符串包含要替换的值的实例,则此方法将无法正常工作。如果需要处理,则需要在开始每次搜索的字符串中提供偏移量:

though it's not a concern with the strings you used, as @ipc pointed out, this doesn't work correctly if the replacement string contains an instance of the value being replaced. If you need to deal with that, you'll need to supply the offset in the string at which to start each search:

int pos = 0;

while ((pos = x.find(old, pos)) != std::string::npos) {
    x.replace(pos, old.length(), rep);
    pos += rep.length();
}

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

Or, you might prefer a for loop in this case:

    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);
}

这篇关于用一些字符串替换字符串中的char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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