fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. void split(const std::string& s) {
  5. size_t sz = s.size();
  6. size_t half_sz = sz / 2;
  7. std::string left = s.substr(0, half_sz);
  8. std::string right;
  9.  
  10. if ((sz % 2) == 0) {
  11. right = s.substr(half_sz, half_sz);
  12. } else {
  13. right = s.substr(half_sz + 1, half_sz);
  14. }
  15.  
  16. std::cout << "String: " << s
  17. << "\n* Left: " << left
  18. << "\n* Right: " << right
  19. << '\n' << std::endl;
  20. }
  21.  
  22. int main() {
  23. split("Hello."); // 6 characters, we're good.
  24. split("Heya."); // 5 characters, 'y' will be discarded.
  25. split("abba"); // 4 characters, we're good.
  26. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
String: Hello.
* Left:  Hel
* Right: lo.

String: Heya.
* Left:  He
* Right: a.

String: abba
* Left:  ab
* Right: ba