How to split a string by 1 or more white spaces in C++

1 Answer

0 votes
#include <iostream>
#include <string>

int main() {
    std::string s = "c  c++  \n    c#  \r java  \t  python";
    std::string delimiters = " \n\r\t";
    std::string token;
    std::size_t pos;

    while ((pos = s.find_first_of(delimiters)) != std::string::npos) {
        token = s.substr(0, pos);
        if (token != "") {
            std::cout << token << std::endl;
        }
        s.erase(0, pos + 1);
    }

    if (!s.empty()) {
        std::cout << s << std::endl;
    }
}

 
 
/*
run:
 
c
c++
c#
java
python
 
*/

 



answered Jul 2, 2024 by avibootz

Related questions

1 answer 173 views
1 answer 131 views
1 answer 194 views
1 answer 173 views
2 answers 235 views
1 answer 148 views
2 answers 108 views
...