0

Given a string of which the content could be "this is a test string jump‎ ‏‏‎ ‎‎fox string".

There are 2 things to note from this string - there is one space between every word, but also at a specific point there is two spaces between "jump" and "fox".

I wish to push_back() each individual word into a different index of std::vector, but I do not want to remove whitespace that is length 2 in size. E.g. the space between "jump" and "fox". Whitespace which is 1 in size can be removed.

For example, the following code:

std::stringstream m(string);
std::istream_iterator<std::string> begin(m);
std::istream_iterator<std::string> end;
std::vector<std::string> myvector(begin, end);

Places all individual words into a vector at different indexes, but also removes the whitespace of lengths 1 and 2.

Summarised: I would like to place each word in the string into a separate index of std::vector. There must be no whitespace after any word in any index. There must be no whitespace of length 1 in any index on its own. Only whitespace of length 2 i.e. between "jump" and "fox" should be placed into its own std::vector index.

I am aware that this is a very niche question, but I am sure there must be a way around this.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mutlithrd
  • 21
  • 4
  • split the string at two whitespaces then split the resulting strings at single whitespace. – 463035818_is_not_an_ai Nov 02 '22 at 14:31
  • 2
    Simply iterate through the string, character by character, implementing the appropriate logic to do this. Here's how to figure this out, this always works! Take out a blank sheet of paper. Write down a step-by-step process of doing this, as short, brief sentences in plain English. [Have your rubber duck review your plan](https://en.wikipedia.org/wiki/Rubber_duck_debugging). After your rubber duck approves your proposed plan of action, simply take what you've written down and translate it directly into C++, and you're done! Have you discussed this with your rubber duck, yet? – Sam Varshavchik Nov 02 '22 at 14:33
  • [std::adjacent_find](https://en.cppreference.com/w/cpp/algorithm/adjacent_find), and have the stop condition be two consecutive spaces. – PaulMcKenzie Nov 02 '22 at 14:43
  • 1
    If it's really only about single/double space, just copy-paste this solution https://stackoverflow.com/a/46931770/4165552 to split a string, and then substitute every empty element with double space. – pptaszni Nov 02 '22 at 14:44
  • @Mutlithrd Given your exaple string, what do you want the `vector` to look like, exactly? Your description sounds like you want this: `["this", "is", "a", "test", "string", "jump‎", " ", ‎‎"fox", "string"]`, is that right? – Remy Lebeau Nov 02 '22 at 19:30

0 Answers0