Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There A Built-In Way to Split Strings In C++?

Tags:

c++

string

split

well is there? by string i mean std::string

like image 328
jimi hendrix Avatar asked Mar 01 '09 15:03

jimi hendrix


6 Answers

Here's a perl-style split function I use:

void split(const string& str, const string& delimiters , vector<string>& tokens)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
like image 56
heeen Avatar answered Oct 10 '22 04:10

heeen


There's no built-in way to split a string in C++, but boost provides the string algo library to do all sort of string manipulation, including string splitting.

like image 32
Martin Cote Avatar answered Oct 10 '22 04:10

Martin Cote


Yup, stringstream.

std::istringstream oss(std::string("This is a test string"));
std::string word;
while(oss >> word) {
    std::cout << "[" << word << "] ";
}
like image 37
MSalters Avatar answered Oct 10 '22 06:10

MSalters


STL strings

You can use string iterators to do your dirty work.

std::string str = "hello world";

std::string::const_iterator pos = std::find(string.begin(), string.end(), ' '); // Split at ' '.

std::string left(str.begin(), pos);
std::string right(pos + 1, str.end());

// Echoes "hello|world".
std::cout << left << "|" << right << std::endl;
like image 21
strager Avatar answered Oct 10 '22 04:10

strager


void split(string StringToSplit, string Separators)
{
    size_t EndPart1 = StringToSplit.find_first_of(Separators)
    string Part1 = StringToSplit.substr(0, EndPart1);
    string Part2 = StringToSplit.substr(EndPart1 + 1);
}
like image 29
Igor Avatar answered Oct 10 '22 06:10

Igor


The answer is no. You have to break them up using one of the library functions.

Something I use:

std::vector<std::string> parse(std::string l, char delim) 
{
    std::replace(l.begin(), l.end(), delim, ' ');
    std::istringstream stm(l);
    std::vector<std::string> tokens;
    for (;;) {
        std::string word;
        if (!(stm >> word)) break;
        tokens.push_back(word);
    }
    return tokens;
}

You can also take a look at the basic_streambuf<T>::underflow() method and write a filter.

like image 29
dirkgently Avatar answered Oct 10 '22 05:10

dirkgently