How to split a string into words in C++

2 Answers

0 votes
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <string>

std::vector<std::string> SplitString(const std::string& s)
{
    std::istringstream iss(s);
    std::vector<std::string> tokens;

    std::copy(std::istream_iterator<std::string>(iss),
              std::istream_iterator<std::string>(),
              std::back_inserter(tokens));

    return tokens;
}

int main()
{
    std::string s = "C++ C C# Java PHP";

    std::vector<std::string> tokens = SplitString(s);

    for (const auto& word : tokens)
        std::cout << word << std::endl;
}


 
/*
run:
 
C++
C
C#
Java
PHP
 
*/
 

 



answered Feb 4, 2017 by avibootz
edited Aug 29 by avibootz
0 votes
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>

std::vector<std::string> SplitStringMultiDelim(const std::string& s,
                                               const std::string& delims)
{
    std::string temp = s;

    // Replace each delimiter with a space
    for (char d : delims)
        std::replace(temp.begin(), temp.end(), d, ' ');

    std::istringstream iss(temp);
    std::vector<std::string> tokens;

    std::string word;
    while (iss >> word)
        tokens.push_back(word);

    return tokens;
}

int main()
{
    std::string s = "-c, c++.. c#:: -java ,php...python";

    // delimiters: space, comma, dot, colon, dash
    std::string delims = " ,.: -";

    std::vector<std::string> tokens = SplitStringMultiDelim(s, delims);

    for (const auto& w : tokens)
        std::cout << w << std::endl;
}


/*
run:

c
c++
c#
java
php
python

*/

 



answered Feb 4, 2017 by avibootz
edited Aug 29 by avibootz
...