fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. typedef std::string::size_type pos_t;
  5.  
  6. std::string cleanLinks (const std::string & s)
  7. {
  8. pos_t openBrackets = s.find("[[");
  9. // Set the result as anything before the first link.
  10. std::string result = s.substr(0,openBrackets);
  11. if ( std::string::npos == openBrackets )
  12. return result;
  13.  
  14. // Search on from the first opening brackts to the closing brackets.
  15. pos_t closeBrackets = s.find("]]", openBrackets);
  16. if ( std::string::npos == closeBrackets )
  17. return result;
  18.  
  19. // At this point, result contains anything up to the first link ("[[").
  20. // If there are no links, we won't get here.
  21.  
  22. // Make a string consisting of just the (first) link.
  23. std::string linkStr = s.substr(openBrackets, closeBrackets-openBrackets+2);
  24.  
  25. // If the link contains a |, split it out into text, and add that to
  26. // the result. Otherwise add the whole thing to the result unchanged.
  27. pos_t pipePos = linkStr.find("|");
  28. if ( std::string::npos == pipePos )
  29. {
  30. result += linkStr;
  31. }
  32. else
  33. {
  34. result += linkStr.substr(2, pipePos-2);
  35. }
  36.  
  37. // Clean up any links in the rest of the string, then give it all back.
  38. return result + cleanLinks(s.substr(closeBrackets+2, std::string::npos));
  39. }
  40.  
  41. int main()
  42. {
  43. std::string inp =
  44. "This is a link [[abcd 1234|xyz 1234]] "
  45. "[[India]] [[abcd 1234|xyz 1234]]";
  46. std::cout << '\"' << inp << "\"\n\"" << cleanLinks(inp) << "\"\n";
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
"This is a link [[abcd 1234|xyz 1234]]  [[India]] [[abcd 1234|xyz 1234]]"
"This is a link abcd 1234  [[India]] abcd 1234"