开发者

How to split a string? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

i have one string varia开发者_如何学运维ble which contains: string var = "this_is.that_alos" how i can separate only "that_alos" from it. i.e. i need only second part after "that_alos"


std::string var = "this_is.that_alos";
std::string part = var.substr(var.find_first_of('.'));

If you want to exclude the '.', just add 1:

std::string part = var.substr(var.find_first_of('.') + 1);


In C, the usual function is strchr(3):

char * second_half = strchr(var, '.');

Of course, this is just a new pointer to the middle of the string. If you start writing into this string, it changes the one and only copy of it, which is also pointed to by char *var. (Again, assuming C.)


std::string var = "this_is.that_alos";

std::string::iterator start = std::find(var.begin(), var.end(), '.')
std::string second(start + 1, var.end());

But you should check if start + 1 is not var.end(), if var don't contain any dot.


If you don't want to use string indexing or iterators, you can use std::getline

std::string var = "this_is.that_alos";
std::istringstream iss(var);

std::string first, second;

std::getline(iss, first, '.');
std::getline(iss, second, '.');


The easiest solution would be to use boost::regex (soon to be std::regex). It's not clear what the exact requirements are, but they should be easy to specify using a regular expression.

Otherwise (and using regular expressions could be considered overkill for this), I'd use the usual algorithms, which work for any sequence. In this case, std::find will find the first '.', use it with reverse iterators to find the last, etc.

-- James Kanze


Use strtok for splitting the String, with the Special character as "." for ex

string var = "this_is.that_alos";
string Parts[5] = strtok(&var[0],".");
string SubPart = Parts[1];

Hope it will help U.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜