-1

How to split a string(extract words) without stringstream and strtok in C++?

I want to split a string that has multiple consecutive spaces between each word, and it may span multiple lines as well have white space before a new line start.

So far I have this but it can only handle one space

while (input.compare(word) != 0)
{
   index = input.find_first_of(" ");
   word = input.substr(0,index);
   names.push_back(word);
   input = input.substr(index+1, input.length());
}

Thank you

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
Sdiii
  • 1
  • 3
  • Possible duplicate of [How do I tokenize a string in C++?](https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) – Joseph D. Apr 25 '18 at 01:18
  • *How to split a string(extract words) without stringstream and strtok in C++* -- Use `boost::algorithm::split`. Also, why don't you want to use `stringstream`? – PaulMcKenzie Apr 25 '18 at 01:18
  • just don't push_back if word is empty – kmdreko Apr 25 '18 at 01:19
  • For example like [this](https://github.com/crusader-mike/parray). See example at "Split string and process every part without mem alloc". Just use _split_se()_ instead of _split()_ – C.M. Apr 25 '18 at 01:51
  • @codekaizer Thank you for the link but all the codes there use libraries that I don't want. – Sdiii Apr 25 '18 at 02:48
  • @PaulMcKenzie just a requirement I have and i can't use that either. – Sdiii Apr 25 '18 at 02:50
  • @vu1p3n0x thank you. – Sdiii Apr 25 '18 at 02:50

1 Answers1

0

Here's a reference:

std::string input = "   hello   world   hello    "; // multiple spaces
std::string word = "";
std::vector<std::string> names;

while (input.compare(word) != 0)
{
   auto index = input.find_first_of(" ");
   word = input.substr(0,index);

   input = input.substr(index+1, input.length());

   if (word.length() == 0) {
      // skip space
      continue;
   }

   // Add non-space word to vector
   names.push_back(word);
}

Check in Wandbox

Joseph D.
  • 11,804
  • 3
  • 34
  • 67