【问题标题】:Parse string and swap substrings [closed]解析字符串并交换子字符串 [关闭]
【发布时间】:2013-07-03 19:29:28
【问题描述】:

如何解析用户给出的字符串并将所有出现的旧子字符串与新字符串交换。我有一个可以使用的函数,但在字符串方面我真的不确定。

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

【问题讨论】:

  • 这是家庭作业吗?
  • 我们可以看看你到目前为止尝试过的代码吗?
  • 这是用 C 还是 C++ 编写的?如果是 C++,请使用 std::string。如果是 C,请适当标记。
  • 问题必须表明对正在解决的问题有最低限度的了解。告诉我们您尝试过什么,为什么它不起作用,以及它应该如何工作。另请参阅:堆栈溢出问题清单

标签: c++ c string


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    // 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; 
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 2020-03-31
      • 2016-06-29
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      相关资源
      最近更新 更多