parse a char vector to different strings

65 Views Asked by At

I have a character vector like

std::vector<char> input({'{', 'a', 'b','}',\0', '{','c','d','}',\0','\0','\0'});

I want to parse this to have strings

string1="ab"
string2="cd"

How to achieve this as vector has trailing '\0' characters.

Tried something like below. but going into infinite loop

td::vector<char> input({ 'a', 'b','\0', 'c','\0'});
std::vector<std::string> list;
std::string s(input.begin(), input.end());
size_t pos = 0;
std::string token;
while ((pos = s.find('\0')) != std::string::npos) {     
token = s.substr(0, pos);
s.erase(0, pos);
list.push_back(token);
}

1

There are 1 best solutions below

0
Alexsen On

Not 100% sure, but I doubt s.find('\0') should return the first occurrence of \0, which means that if string(assume a string) is abcd\0ef, .find() should return index 4. In this case, erasing 4 characters from position 0 means you are erasing abcd part of the string, while leaving \0 still there. This is most likely causing the infinite loop.

To make sure, print the pos value to check what index it is before erasing.

Also, note that this approach will be quite slow, since .erase() is O(n) where n=string.size(), thus .substr() is also slow, with time complexity of substring size.