C++ Primer 第五版 中文版 练习 9.43 9.44

原题:编写一个函数,接受三个string参数s、oldVal和newVal。使用迭代器及insert和erase函数将s中所有oldVal替换为newVal。 测试你的程序,用它替换通用的简写形式,如,将tho替换为though,将thru替换为“through”。

网上搜到了一个使用 substr() 的答案,感觉原题里这个条件“使用迭代器、insert、erase” 是不允许使用其他函数的。

void replaceString(std::string &s, const std::string &oldVal, const std::string &newVal){

  if (oldVal.empty() || s.empty()){
      return;
  }

  if (s.size() < oldVal.size()){
      return;
  }

  auto sIter = s.begin();
  auto oldIter = oldVal.begin();

  while (sIter != s.end()){
    
      if ((*sIter) == (*oldIter)){
          ++oldIter;
      }else {
          oldIter = oldVal.begin();
      }
    
      ++sIter;
    
      if (oldIter == oldVal.end()){
          oldIter = oldVal.begin();
          sIter = s.erase(sIter - oldVal.size(), sIter);
          for (std::string::size_type index = 0; index < newVal.size(); ++index){
              sIter = s.insert(sIter, newVal[index]);
              ++sIter;
          }
      }
  }

}

还有 9.44 使用下标和 replace 的版本

void replaceString(std::string &s, const std::string &oldVal, const std::string &newVal){

  if (oldVal.empty() || s.empty()){
      return;
  }

  if (s.size() < oldVal.size()){
      return;
  }

  std::string::size_type sIndex = 0;
  std::string::size_type oldIndex = 0;

  while (sIndex < s.size()){
    
    if (oldVal[oldIndex] == s[sIndex]){
        ++oldIndex;
    }else {
        oldIndex = 0;
    }
    
    ++sIndex;
    
    if (oldIndex >= oldVal.size()){
        oldIndex = 0;
        s.replace(sIndex - oldVal.size(), oldVal.size(), newVal);
        sIndex += newVal.size() - oldVal.size();
    }
    
  }
}

你可能感兴趣的:(C++ Primer 第五版 中文版 练习 9.43 9.44)