I just need to get the second word of a string, for example if the string is:
string comanda = "Hello world"
And I only want "world", all I have to do is:
- comanda=comanda.substr(comanda.find_first_of(" \t")+1);
But if the string is = "Hello world" and I don`t know the number of blankspaces that can have.
Thanks
Last edited on
Here's one way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <string>
std::string second_word(const std::string& s) {
const auto npos = std::string::npos;
const auto white_space = " \t\v\n";
// find word break:
auto first_ws = s.find_first_of(white_space);
if (first_ws == npos) return std::string();
// Find beginning of word:
auto word_begin = s.find_first_not_of(white_space, first_ws);
if (word_begin == npos) return std::string();
// find next word break:
auto word_end = s.find_first_of(white_space, word_begin);
return s.substr(word_begin, word_end-word_begin);
}
int main() {
const std::string strings [] = {
"oneword",
"two words",
"three two one",
"four three two one"
};
for (auto&s : strings)
std::cout << "The second word in \"" << s << "\" is \"" << second_word(s) << "\"\n";
}
| |
While it's not difficult to fix, this code will report the first word as the second word if any whitespace precedes the first word.
"Hello" and "world" is separated by a space(" ") not a space and a tab. |
Not relevant, you have a misconception about what
std::string::find_first_of does.
Last edited on