How to split a string in half but not in the middle of a word with C++

1 Answer

0 votes
#include <iostream>
 
int main() {
    std::string str = "c# c java c++ python go";

    std::string halfstr = str.substr(0, str.length() / 2 + 1);
    size_t center = halfstr.find_last_of(' ') + 1;
     
    std::string firstHalf = str.substr(0, center);
    std::string secondHalf = str.substr(center);
 
    std::cout << firstHalf << "\n";
    std::cout << secondHalf << "\n";
}
 
 
 
 
/*
run:
 
c# c java 
c++ python go

*/

 



answered Aug 9, 2023 by avibootz
edited Sep 10, 2024 by avibootz
...