开发者

Learn CPP: Split string and manipulation? [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Closed 11 years ago.

Possible Duplicate:

Remove spaces from std::string in C++

I am starting to learn cpp. Hope you guys can help me. Right now, I am having a problem with strings. I get input from the user and want to ignore the white space and combine the string. Here it is:

getline(cin, userInput);

If user input is: Hello my name is

I want to combine to: Hellomynameis

Is there a quick way to do that. Your help will be much appreciated. Thanks.

EDIT:

And, for another case: if the user input is: keyword -a argument1 argument2 argument3

How do I separate the words, because I want to check what are the "keyword", "option", and the arguments.


You can use:

remove_if(str.begin(), str.end(), ::isspace); 

The algorithm only changes the values and not the container contained values, So you need to call string::erase to actually modify the length of the container after calling remove_if.

str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); 

or if you are a Boost Fan, You can simple use:

erase_all(str, " "); 


Use a istringstream if you just want to separate words:

istringstream iss(userInput)
iss >> blah1 >> blah2 ...

blah1 can be any type. If blah1 is a float, for example, then the iss >> blah1 will try to convert the word to a float (like the C function atof).

If you want to do argument parsing, getopt library is probably what you are looking for. It's what drives the argument parsing for most of the gnu command line utilities (like ls)


For getting rid of the space what @Als suggested is right.

For parsing the command line arguments: You can probably use a library i.e.

boost::program_options(http://www.boost.org/doc/libs/1_47_0/doc/html/program_options.html),

or getopt

or libargh(http://bisqwit.iki.fi/source/libargh.html)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜