解析字符串和交换子字符串

时间:2013-07-03 19:29:28

标签: c++ c string

如何解析用户给出的字符串,并将所有出现的旧子字符串与新字符串交换。我有一个可以使用的功能,但是我很不确定它是什么。

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

2 个答案:

答案 0 :(得分:2)

最简单的解决方案是在这里使用谷歌(First link)。另请注意,在C ++中,我们更喜欢std::string而不是const char *。不要编写自己的std::string,使用内置的{{1}}。您的代码似乎比C ++更强 C

答案 1 :(得分:0)

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