【问题标题】:Searching and replacing all occurrence of a string in a char array c++在char数组c ++中搜索和替换所有出现的字符串
【发布时间】:2016-05-12 01:52:24
【问题描述】:

我有一个 char 数组,我想找到特定子字符串的所有位置,然后我将用不同的东西替换所有子字符串。

例如:

char [35] = "the boy stole the cup from the table.";

1。我想打印出"the" 所在的每个位置。我找到了一些像find 这样的函数,但它只能找到我想要的第一个位置。我尝试使用循环,但也没有成功。

  1. 我还想用"that" 之类的东西替换所有出现的"the" 有人可以告诉我如何实现这一目标。而且我正在专门使用 char 数组而不是字符串类。

【问题讨论】:

  • strstr 为您提供第一场比赛的开始(作为字符指针);如果您随后开始搜索至少一个字符,那么您将获得第二个匹配项(如果有)。至于算法,您只需复制第一次匹配之前的部分,附加替换字符串,跳过搜索字符串,然后再次匹配。如果您可以向我们展示一些代码以及您遇到的具体问题?
  • 向我们展示您迄今为止的尝试以及您遇到的问题。这不是代码编写服务。
  • I have found some functions like find but it only finds the first position of what I want. I tried using a loop but that did not also work out. 然后你错误地使用了find,因为这正是你解决这个问题的方法。发布您的代码。
  • 那句话包含 38 个字符。您将如何在 char[35] 中准确存储 38 个字符?更重要的是,如果将“the”替换为“that”,它现在是 41 个字符。

标签: c++ arrays search replace char


【解决方案1】:

试试这个功能。我认为它会起作用。

void find_and_replace(string& source, string const& find, string const& replace)
{
    for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;)
    {
        source.replace(i, find.length(), replace);
        i += replace.length();
    }
}


   content = "this is c++ programming";

   find_and_replace(content, "c++", "java");

【讨论】:

  • replace.length() 存储在for 循环之前的变量中,以避免可能多次调用该函数(以提高性能)。与find.length() 相同。
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 2012-08-01
  • 2021-07-12
  • 1970-01-01
  • 2021-12-27
  • 2011-10-20
  • 1970-01-01
  • 2014-03-26
相关资源
最近更新 更多