fork(4) download
  1. #include <string>
  2. #include <iostream>
  3. #include <algorithm>
  4.  
  5. std::string cutAtNComma(const std::string &s, int n) {
  6. auto iter = std::find_if(s.cbegin(), s.cend(),
  7. [n](char c) mutable {
  8. if (c == ',') {
  9. if (--n == 0) return true;
  10. }
  11. return false;
  12. }
  13. );
  14. if (iter != s.cend()) return std::string(s.cbegin(), iter);
  15. return s;
  16. }
  17.  
  18. int main() {
  19. std::string s1 = "item1, item2, item3, item4, item5";
  20. std::string sub = cutAtNComma(s1, 4);
  21. std::cout << "String is: " << sub;
  22. return 0;
  23. }
Success #stdin #stdout 0s 4492KB
stdin
Standard input is empty
stdout
String is: item1, item2, item3, item4