比较 char* 和 wchar_t* 类型的 C 字符串

Compare C-string of types char* and wchar_t*

本文关键字:类型 字符串 char wchar 比较      更新时间:2023-10-16

我有一个这样的key

wchar_t key[] = L"764frtfg88fgt320nolmo098vfr"; 

以及从数据库查询返回的char* row[i]

我想将我的Keyrow[i]进行比较。我试过

wcscmp (key,row[i]) != 0)

但它给了我一个错误。有什么建议吗?

这可能会有所帮助: C++ 将字符串(或字符*)转换为字符串(或wchar_t*)

总结一下:

#include <string>
wchar_t Key[] = L"764frtfg88fgt320nolmo098vfr";
std::wstring k(Key);
const char* text = "test"; // your row[i]
std::string t(text);
// only works well if the string being converted contains only ASCII characters.
std::wstring a(t.begin(), t.end()); 
if(a.compare(k) == 0)
{   
    std::cout << "same" << std::endl;
}

我会使用C++工具:

#include <iostream>
#include <string>
// construct a wstring from a string
std::wstring to_wstring(std::string const& str)
{
    const size_t len = ::mbstowcs(nullptr, &str[0], 0);
    if (len == size_t(-1)) {
        throw std::runtime_error("to_wstring()");
    }
    std::wstring result(len, 0);
    ::mbstowcs(&result[0], &str[0], result.size());
    return result;
}

//
// TEST CASES ---
//
const wchar_t key[] = L"764frtfg88fgt320nolmo098vfr"; 
const auto wkey = std::wstring(key);
bool operator==(std::string const& lhs, std::wstring const& rhs)
{
    return to_wstring(lhs) == rhs;
}
bool operator==(std::wstring const& lhs, std::string const& rhs) { return rhs == lhs; }
int main() {
    std::cout << std::boolalpha << ("hello" == wkey) << "n"
                                << (wkey == "764frtfg88fgt320nolmo098vfr") << "n";
}

指纹

false
true

的好处是它(应该)在 *nix 和 Windows 上使用非 ASCII 字符。

已经有其他答案了,但您也可以像这样将 char* 转换为 wchat_t*。

声明以下内容:

const wchar_t *GetWC(const char *c)
{
    const size_t cSize = strlen(c)+1;
    wchar_t* wc = new wchar_t[cSize];
    mbstowcs (wc, c, cSize);
    return wc;
}

然后像这样使用它:

wchar_t * temprow;
temprow = (wchar_t *)GetWC(row[i]);
/* replace following line with your own */
std::cout << "i " << i << " is " << (wcscmp (key,temprow) != 0) << "n";
/* avoid memory leak */
free(temprow);

感谢这个线程:如何将字符*转换为wchar_t*?