I have an array of WCHAR[]s. How can I join them?
I know the array length.
[L"foo", L"bar"] => "foo, bar"
I have an array of WCHAR[]s. How can I join them?
I know the array length.
[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])
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]);