Remove/Replace charactors in std::string

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_16849135/article/details/89551151

This is a way to remove all spaces in a string:

std::string removeSpace(const std::string& str){
  std::string strToRemove = " ";
  std::string ret(str);
  
  size_t pos = ret.find(strToRemove);
  whilt(pos != std::string::npos){
    ret = ret.replace(pos, strToRemove.length(), "");
    pos = ret.find(strToRemove);
  }
  
  return ret;
}


std::string source = "Hello World";
source = removeSpace(source);  // source -> "HelloWorld"

You can also use the same way to replace or remove other charactors:

std::string replace(const std::string& strToConvert,
                    const std::string& strToReplace,
                    const std::string& strToReplaceBy){
  std::string ret(strToConvert);
  size_t pos = ret.find(strToReplace);

  while(pos != std::string::npos){
    ret = ret.replace(pos, strToReplace.length(), strToReplaceBy);
    pos = ret.find(strToReplace);
  }

  return ret;
}

std::string source = "Hello C++";
source = replace(source, "+", "p"); // source -> "Hello Cpp"

猜你喜欢

转载自blog.csdn.net/qq_16849135/article/details/89551151