Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting strings in C++ [duplicate]

Tags:

c++

string

token

How do you split a string into tokens in C++?

like image 862
BobS Avatar asked Nov 09 '08 00:11

BobS


People also ask

Can you split a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

How does strtok work in C?

The first time the strtok() function is called, it returns a pointer to the first token in string1. In later calls with the same token string, the strtok() function returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are null-ended.

What is a delimiter in C?

In computer programming, a delimiter is a character that identifies the beginning or the end of a character string (a contiguous sequence of characters).


1 Answers

this works nicely for me :), it puts the results in elems. delim can be any char.

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}
like image 195
Evan Teran Avatar answered Oct 02 '22 13:10

Evan Teran