分析字符串并交换子字符串

Parse string and swap substrings

本文关键字:字符串 交换 串并 字符      更新时间:2023-10-16

如何解析用户给定的字符串,并用新字符串替换所有出现的旧子字符串。我有一个函数要处理,但当涉及到字符串时,我真的很不确定。

void spliceSwap( char* inputStr, const char* oldStr, const char* newStr  )

最简单的解决方案是在这里使用谷歌(第一个链接)。还要注意,在C++中,我们更喜欢std::string而不是const char *。不要编写自己的std::string,使用内置的。您的代码似乎更像是C而不是C++!

// Zammbi's variable names will help answer your  question   
// params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   // ASSERT(find != NULL);
   // ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;
   // search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      // replace the found string with the replacement
      source.replace( pos, findLen, replace );
      // the next line keeps you from searching your replace string, 
      // so your could replace "hello" with "hello world" 
      // and not have it blow chunks.
      pos += replaceLen; 
   }
}