【问题标题】:Concatenation of LPWSTR strings连接 LPWSTR 字符串
【发布时间】:2013-03-03 12:03:37
【问题描述】:

在 Visual C++ 中,我有一个

LPWSTR mystring;

已经在代码的其他地方定义了。

我想创建一个新的 LPWSTR,其中包含:

"hello " + mystring + " blablabla"        (i.e. a concatenation)

我对这么简单的事情(串联)感到很生气!提前非常感谢,我迷路了!

【问题讨论】:

  • 作为 Unix 开发者,LPWSTR!?!?!投反对票,完全不合适。
  • @AlexChamberlain 这是一个宽字符串类型(AFAIK,这里也是 Unix 开发)。另一个来自 Win(cr)API 的无脑 typedef。
  • 可能是我见过的最糟糕的typedefs 之一!
  • 这与 Visual C++ 无关,所以我删除了该标签并添加了 WinAPI。
  • @ShmilTheCat:你为什么要浪费你生命中的 1 分钟对我说“Google on ...”一分钟:你真的认为我还没有做到吗?

标签: c++ string winapi concatenation string-concatenation


【解决方案1】:
std::wstring mystring_w(mystring);
std::wstring out_w = L"hello " + mystring_w + L" blablabla";
LPWSTR out = const_cast<LPWSTR>(out_w.c_str());

'out' 是 'out_w' 的 LPWSTR 包装器。因此,只要“out_w”在范围内,它就会很好用。此外,您不需要删除 'out',因为它已绑定到 'out_w' 生命周期。

这与“user529758”给出的答案几乎相同,但建议修改为“chris”。

【讨论】:

    【解决方案2】:

    C++ 方式:

    std::wstring mywstring(mystring);
    std::wstring concatted_stdstr = L"hello " + mywstring + L" blah";
    LPCWSTR concatted = concatted_stdstr.c_str();
    

    【讨论】:

    • 一个修改是concatted必须是LPCWSTR
    【解决方案3】:

    你可以使用StringCchCatW函数

    【讨论】:

    • 那不是 C++,或者当然不应该。
    • @AlexChamberlain 问题是关于 Visual C++
    • @JacobSeleznev 完全不相关;它不是现代 C++。
    • @Alex LPWSTR 不是现代 C++,所以我们已经在那个领域之外了。如果在问题的域内存在一个实用的解决方案,为什么要限制现代 C++ 的解决方案呢?正如我上面所说,他最终还是需要将结果转换回LPWSTR
    • @JBentley 因为这就变成了安全性和清晰度的问题。
    猜你喜欢
    • 1970-01-01
    • 2012-09-09
    • 2014-07-31
    • 1970-01-01
    • 2014-03-31
    • 2010-10-17
    相关资源
    最近更新 更多