开发者

C++: Join an array of WCHAR[]s?

开发者 https://www.devze.com 2023-01-02 14:20 出处:网络
I have an array of WCHAR[]s. How can I join them? I know the array lengt开发者_如何转开发h. [L\"foo\", L\"bar\"] => \"foo, bar\"

I have an array of WCHAR[]s. How can I join them?

I know the array lengt开发者_如何转开发h.

[L"foo", L"bar"] => "foo, bar"


Loop over those strings and add them to a std::wstring:

std::wstring all;

wchar_t *data[] = { L"foo", ... };
size_t data_count = sizeof(data) / sizeof(*data);

for (size_t n = 0; n < data_count; ++n)
{
    if (n != 0)
        all += L", ";
    all += data[n];
}


Does your system have wsprintf()? Example:

wchar_t *a = { L"foo", L"bar" };
wchar_t joined[1000];

wsprintf(joined, "%S, %S", a[0], a[1])


This seems like a good job for a template function. I use this function for joining strings, but it takes any container that supports forward iterators:

template<typename oT, typename sepT, typename rT = oT> rT joinContainer(const oT & o, const sepT & sep) {
    rT out;
    auto it = o.begin();
    while(it != o.end()) {
        out += *it;
        if(++it != o.end()) out += sep;
    }
    return out;
}

You can call it like this:

vector<wstring> input = { L"foo", L"bar", L"baz" };
wstring out = joinContainer<vector<wstring>, wstring, wstring>(input, L", ");;
wcout << out << endl;

The output looks like this:

foo, bar, baz

Note: If you're not using C++11, you can declare the iterator like this instead of using auto:

typename oT::const_iterator it = o.begin();


Slightly improved version of R Samuel Klatchko's solution.

wchar_t *data[] = { L"foo", ... };
size_t data_count = sizeof(data) / sizeof(*data);

wchar_t result[STUFF];

wcscpy(result, data[0]);
for (std::size_t n = 1; n < data_count; ++n)
{
    wcscat(result, L", ");
    wcscat(result, data[n]);
}

The improvement is that no if branch dependency is in the loop. I have converted to the C standard library's wcsXXXX functions, but I'd use a std::wstring if it is available.

EDIT:

Assuming

I know the array length.

means, "I know the number of strings I'd like to join", then you can't use what I've posted above, which requires you know the final destination string length at compile time.

If you don't know at compile time, use this which works otherwise (and contains the loop improvement I was talking about):

wchar_t *data[] = { L"foo", ... };
size_t data_count = sizeof(data) / sizeof(*data);

std::wstring result(data[0]); //Assumes you're joining at least one string.
for (std::size_t n = 1; n < data_count; ++n)
    result.append(L", ").append(data[n]);
0

精彩评论

暂无评论...
验证码 换一张
取 消