Aw: char array nummterminated to std::vector<std::string>

S

Syron

As the strings are separated by NUL chars and I simply assume that the final end of the char* will be marked by two NUL chars immediately following each other (thus the last string will be a "virtual" string with length 0), I suggest the following:

typedef std::vector<std::string> StringVec;

StringVec nulSplit(const char* input) {
StringVec result;
while(input[0] != 0) {
std::string token(input);
result.push_back(token);
input += token.length()+1; // +1 to skip NUL char
}
return result;
}
 
P

Paul

Syron said:
As the strings are separated by NUL chars and I simply assume that the
final end of the char* will be >marked by two NUL chars immediately
following each other (thus the last string will be a "virtual" string
Maybe there could also be three '\0's at the end, so you will still need to
know the length of the input.
In one of the posts the OP said he knows the length of the input c-strings
so that length will be known
..
typedef std::vector<std::string> StringVec;

StringVec nulSplit(const char* input) {
StringVec result;
while(input[0] != 0) {
std::string token(input);
result.push_back(token);
input += token.length()+1; // +1 to skip NUL char
}
return result;
}
This actually does not work when I tried it.
Each iteration of the while loop:
creates a temp string object;
invokes a call to push_back;
invokes a call to length();

But the use of any '\0' in the input c-string can be used to mark the size
of the pushed string.
Here is what I came up with when using this method:

std::vector<std::string> split_str(char* in, int len){
std::vector<std::string> out;
if(*in != '\0')out.push_back(in);
for(int i=1; i<len; ++i){
if(in[i-1]=='\0'){
if(in!= '\0')
out.push_back(in+i);
}
}
return out;
}

int main(){
char arr[] = "\0dsfsf\0segser\0fwrwr\0\0grh\0grht\0";
std::vector<std::string> v = split_str(arr, sizeof(arr));

/*Code to display vector contents*/
std::cout<<"size of vector = "<<v.size()<< std::endl;
for(int i=0;i <v.size(); ++i){
std::cout<< "v["<<i<<"] = " << v << std::endl;
}
/***** ******/
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top