fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. bool ends_with(std::string const & str, std::string const & suffix)
  6. {
  7. // If the string is smaller than the suffix then there is no match.
  8. if (str.size() < suffix.size()) { return false; }
  9.  
  10. return 0 == str.compare(str.size() - suffix.size(),
  11. suffix.size(),
  12. suffix,
  13. 0,
  14. suffix.size());
  15. }
  16.  
  17. void ensure_ends_with_txt(std::string & str)
  18. {
  19. if (!ends_with(str, ".txt")) {
  20. str += ".txt";
  21. }
  22. }
  23.  
  24. int main() {
  25. std::vector<std::string> tests = {
  26. "a.txt",
  27. "b.txt.zip",
  28. "c"
  29. };
  30.  
  31. for (auto i = tests.begin(); i != tests.end(); ++i) {
  32. std::cout << *i << " --> ";
  33. ensure_ends_with_txt(*i);
  34. std::cout << *i << std::endl;
  35. }
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
a.txt --> a.txt
b.txt.zip --> b.txt.zip.txt
c --> c.txt