String parse separated by null values

Asked

Viewed 88 times

1

I am using the OpenFileName winapi with multiselect flag. When the user selects several files he returns me a string separated by nulls according to the following model:

"[caminho da pasta]\0[arquivo 1]\0[arquivo 2]\0[arquivo 3]\0\0"

How could I turn this string into an array? Is there any method of the c++ itself for this? If not, how can I identify the "\0" in for?

1 answer

4


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

const char* data = "[caminho da pasta]\0[arquivo 1]\0[arquivo 2]\0[arquivo 3]\0\0";

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

const char* str1 = data;
int len1 = strlen(str1);

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

const char* str2 = str1 + len1 + 1;
int len2 = strlen(str2);

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

You can do it in a loop like this:

int main() {
    const char* data = "[caminho da pasta]\0[arquivo 1]\0[arquivo 2]\0[arquivo 3]\0\0";

    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;
}

Resulting in:

[0] = '[caminho da pasta]'
[1] = '[arquivo 1]'
[2] = '[arquivo 2]'
[3] = '[arquivo 3]'

Functional example (coliru)

  • and this type of loop would work for a wchar_t string?

  • @Raphaelrosa Yes, just use wcslen in place of strlen.

  • cool... thanks even dude

Browser other questions tagged

You are not signed in. Login or sign up in order to post.