String parse separated by null values

1

I'm using OpenFileName of winapi with the flag of multiselect. When the user selects multiple files it returns me a string separated by nulls as follows:

"[caminho da pasta]
"[caminho da pasta]%pre%[arquivo 1]%pre%[arquivo 2]%pre%[arquivo 3]%pre%%pre%"
[arquivo 1]%pre%[arquivo 2]%pre%[arquivo 3]%pre%%pre%"

How could I turn this string into an array? Is there any c ++ method for this? If not, how can I do to identify "%code%" in for?

    
asked by anonymous 28.05.2014 / 16:53

1 answer

4

A string in C is a sequence of characters terminated by a null terminator. So since you have:

const char* data = "[caminho da pasta]
const char* str1 = data;
int len1 = strlen(str1);
[arquivo 1]
const char* str2 = str1 + len1 + 1;
int len2 = strlen(str2);
[arquivo 2]
int main() {
    const char* data = "[caminho da pasta]
[0] = '[caminho da pasta]'
[1] = '[arquivo 1]'
[2] = '[arquivo 2]'
[3] = '[arquivo 3]'
[arquivo 1]
const char* data = "[caminho da pasta]
const char* str1 = data;
int len1 = strlen(str1);
[arquivo 1]
const char* str2 = str1 + len1 + 1;
int len2 = strlen(str2);
[arquivo 2]
int main() {
    const char* data = "[caminho da pasta]
[0] = '[caminho da pasta]'
[1] = '[arquivo 1]'
[2] = '[arquivo 2]'
[3] = '[arquivo 3]'
[arquivo 1]%pre%[arquivo 2]%pre%[arquivo 3]%pre%%pre%"; vector<string> files; const char* str = data; int len = strlen(str); while (len) { files.push_back(string(str, len)); str = str + len + 1; len = strlen(str); } for (unsigned i = 0; i < files.size(); ++i) { cout << "[" << i << "] = '" << files[i] << "'" << endl; } return 0; }
[arquivo 3]%pre%%pre%";
[arquivo 2]%pre%[arquivo 3]%pre%%pre%"; vector<string> files; const char* str = data; int len = strlen(str); while (len) { files.push_back(string(str, len)); str = str + len + 1; len = strlen(str); } for (unsigned i = 0; i < files.size(); ++i) { cout << "[" << i << "] = '" << files[i] << "'" << endl; } return 0; }
[arquivo 3]%pre%%pre%";

You can calculate the size of the first string using strlen :

%pre%

The second string will start after the first and after the null terminator, like this:

%pre%

And so on. You stop when len returns zero, after all the end is marked by a double null marker.

You can do this in a loop like this:

%pre%

Resulting in:

%pre%

Functional example (coliru)

    
28.05.2014 / 17:04