-2

I am splitting a string into smaller pieces based off of the delimiter "/".

stringstream ss(stringToSplit);
string item;
vector<std::string> splitStrings;
while (std::getline(ss, item, delimiter))
{
   splitStrings.push_back(item);
}

some of the strings strings look like this:

home/user/folder
/home/user/folder
banana/grape/onion
/banana/grape/onion

The problem I am having is that the strings that have my delimiter "/" in the front are creating an empty item at the start of the resulting vector. Is there a way to avoid this or to remove the empty item? I have tried removing all " " strings in the vector but they still remain.

Kirby
  • 77
  • 9
  • What hinders you to inspect `item` if the first character is a `/` delimiter, and strip it off (e.g. using `substr()`)? – πάντα ῥεῖ Oct 20 '18 at 09:05
  • @πάντα ῥεῖ: That would work, I'm not sure why I didn't even think of that. I guess since I already asked, is there a way to do what I was originally trying? – Kirby Oct 20 '18 at 09:08

1 Answers1

0

Well, you could just skip empty strings detected by getline() like this:

stringstream ss(stringToSplit);
string item;
vector<std::string> splitStrings;
while (std::getline(ss, item, delimiter))
{
   if(!item.empty()) { // <<<<<<<<<<<<<
       splitStrings.push_back(item);
   }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • That is exactly what I was looking for. Thank You. – Kirby Oct 20 '18 at 09:20
  • @Kirby You might need to consider whitespaces in the input as well. [Here](https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring)'s some information how to do that efficiently. – πάντα ῥεῖ Oct 20 '18 at 09:23