Posted By

kyhle on 07/29/11


Tagged


Versions (?)

Remove specified string in a string


 / Published in: C++
 

  1. #include <iostream>
  2. #include <string>
  3.  
  4. using std::string;
  5. using std::cout;
  6.  
  7. void RemoveSubStr(const string& r, string& str)
  8. {
  9. // Make sure that the strings are not empty;
  10. int rlen = r.length();
  11. int strlen = str.length();
  12.  
  13. if (rlen <= 0 || strlen <=0)
  14. cout << "The string is empty." << '\n';
  15.  
  16. int i,j,pos;
  17.  
  18. for (i = 0; i < strlen; ++i) {
  19. pos = i;
  20. for (j = 0; j < rlen; ++j) {
  21. if (str[i] != r[j]) {
  22. break;
  23. }
  24. else if ( j == (rlen-1)){
  25. str.erase(pos,rlen);
  26. strlen = str.length();// After trimming, the length of string has changed.
  27. i = -1;
  28. }
  29. else
  30. ++i;
  31. }
  32. }
  33. }
  34. int main()
  35. {
  36. string str = "heheo world";
  37. string r = "he";
  38.  
  39. //RemoveSubStr(r,str);
  40.  
  41. // use STL function to remove the substring
  42. int pos = 0;
  43. while (pos != -1){
  44. pos = str.find(r);
  45. if( pos == -1 ) break;
  46. else
  47. str.erase(pos,r.length());
  48. }
  49.  
  50. cout << str << '\n';
  51.  
  52. return 0;
  53. }

Report this snippet  

You need to login to post a comment.