比较 char* 和 wchar_t* 类型的 C 字符串
Compare C-string of types char* and wchar_t*
我有一个这样的key
:
wchar_t key[] = L"764frtfg88fgt320nolmo098vfr";
以及从数据库查询返回的char* row[i]
。
我想将我的Key
与row[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*?
相关文章:
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 类型字符串::长度()。我得到了"Unable to resolve identifier length"
- 如何掩盖对象数组的数据类型字符串到C 中的INT
- 解析参数值 - 字符串和链接值(类型字符串的链接值)与(特定类型的)变量
- C 中的枚举类型字符串类别
- 与基本面作斗争.特别是字符[],字符*和从数组中读取.也许我应该使用类型字符串
- 矢量类型 字符串,但当用整数初始化时
- 如何从const char *类型字符串中删除新线字符
- 在 c++ 中将 ostream 分配给数据类型字符串
- Linux 编译错误 - 无法将类型"字符串"转换为类型"字符串&&"
- LPCSTR 类型字符串出现乱码或显示错误
- C 表达式必须具有类型 - 字符串到const char*
- 将值分配给字符类型字符串
- 将组合框中的类型字符串与其项目进行比较
- 如何将返回类型字符串的数据复制到C++中
- 如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)
- 自定义C类型字符串类的问题
- 在c++中创建自定义C类型字符串类
- 在读取.csv时将数组类型字符串转换为double
- C++将类型字符串变量中的单词转换为小写