【发布时间】:2010-06-04 23:35:04
【问题描述】:
我有一个 WCHAR[] 数组。我怎样才能加入他们?
我知道数组长度。
[L"foo", L"bar"] => "foo, bar"
【问题讨论】:
我有一个 WCHAR[] 数组。我怎样才能加入他们?
我知道数组长度。
[L"foo", L"bar"] => "foo, bar"
【问题讨论】:
遍历这些字符串并将它们添加到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];
}
【讨论】:
int n 更改为无符号类型(最好是size_t)。否则编译器会抱怨。
int / size_t 问题。
你的系统有wsprintf()吗?示例:
wchar_t *a = { L"foo", L"bar" };
wchar_t joined[1000];
wsprintf(joined, "%S, %S", a[0], a[1])
【讨论】:
这对于模板函数来说似乎是一项不错的工作。我使用这个函数来连接字符串,但它需要任何支持前向迭代器的容器:
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;
}
你可以这样称呼它:
vector<wstring> input = { L"foo", L"bar", L"baz" };
wstring out = joinContainer<vector<wstring>, wstring, wstring>(input, L", ");;
wcout << out << endl;
输出如下所示:
foo, bar, baz
注意:如果你没有使用 C++11,你可以像这样声明迭代器而不是使用auto:
typename oT::const_iterator it = o.begin();
【讨论】:
R Samuel Klatchko 解决方案的略微改进版本。
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]);
}
改进之处在于循环中没有if分支依赖。我已转换为 C 标准库的 wcsXXXX 函数,但如果可用,我会使用 std::wstring。
编辑:
假设
我知道数组长度。
意思是“我知道我想加入的字符串的数量”,那么你不能使用我上面发布的内容,这需要你在编译时知道最终的目标字符串长度。
如果您在编译时不知道,请使用其他方法(并且包含我所说的循环改进):
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]);
【讨论】: