开发者

finding multiple ocurrences of a string

How can I find multiple occurrences of a string within a string? And replace the found string with another string in all occurrences? Say, I have the string below:

"A cat is going. It is black开发者_运维问答-white stripped."

I want to replace all occurrences of "is" with are.


You can use Boost::String. IIRC, they have a find_all/replace_all function to do this. Detail here

#include <boost/algorithm/string.hpp> 
#include <iostream> 

int main() 
{ 
  std::string s = "A cat is going. It is black-white stripped."; 
  std::cout << boost::algorithm::replace_all_copy(s, "is", "are") << std::endl; 
} 


string.replace() is what you want. Check it out here. Of course, that will have to be run multiple times, until the string you want replaced returns string::npos on a find(). Try this out:

int main(int argc, char *argv[]) {

  if(argc != 3) {
    cout << "Usage: <binary> <toFind> <toReplace>" << endl;
    exit(1);
  }

  //string str(argv[1]);
  string str = "A cat is going. It is black-white striped.";
  string dest;
  string toFind(argv[1]);
  string toReplace(argv[2]);

  cout << "Original string = " << str << endl;

  while(str.find(argv[1]) != string::npos) {
    size_t pos = str.find(argv[1]);
    str.replace(pos, toFind.length(), toReplace, 0, toReplace.length());
  }

  cout << "Replaced string = " << str << endl;
  return 0;
}

Of course, there are a lot of error-checks that still need to be incorporated into this program. Say, for instance:

  1. str is hard-coded. Not good.
  2. Checks are not made to ensure that the length of the string to be replaced is not larger than str itself.

HTH,
Sriram.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜