搜索和替换字符数组 c++ 中出现的所有字符串

Searching and replacing all occurrence of a string in a char array c++

本文关键字:字符串 替换 字符 数组 c++ 搜索      更新时间:2023-10-16

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

例如:

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

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

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

试试这个函数。 我认为它会起作用。

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