CharConvert.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "CharConvert.h"
  2. #pragma region 字符串编码处理
  3. #pragma region 字符转换
  4. char* CharConvert::StringTocharPtrA(string* sourceStr)
  5. {
  6. char* ch = (LPSTR)(LPCTSTR)sourceStr;
  7. return ch;
  8. }
  9. wchar_t* CharConvert::wstringToWchar_tPtrW(wstring ws)
  10. {
  11. wchar_t* ptr = _wcsdup(ws.c_str());
  12. return ptr;
  13. }
  14. char* CharConvert::GetWstringToCharPtr(wstring ws)
  15. {
  16. wchar_t* ptr = _wcsdup(ws.c_str());
  17. char* ch = CharConvert::GetMultiByteW(ptr);
  18. return ch;
  19. }
  20. #pragma endregion
  21. #pragma region Unicode和ANSI
  22. wstring CharConvert::GetWideCharW(char* multiByte)
  23. {
  24. char* ch = multiByte;
  25. int len = MultiByteToWideChar(CP_ACP, 0, ch, -1, NULL, 0);
  26. wchar_t* wch = new wchar_t[len];
  27. MultiByteToWideChar(CP_ACP, 0, ch, -1, wch, len);
  28. return wch;
  29. }
  30. wstring CharConvert::GetWideCharW(string* multiByte)
  31. {
  32. //(LPSTR)(LPCTSTR)会乱码,之后会在处理所有转换字符的问题
  33. const char* ch2 = /*(LPSTR)(LPCTSTR)*/multiByte->data();
  34. char* ch = (char*)ch2;
  35. wstring wch = GetWideCharW(ch);
  36. return wch;
  37. }
  38. char* CharConvert::GetMultiByteW(wchar_t* wideChar)
  39. {
  40. char* multiByte;
  41. int iwstrLen = WideCharToMultiByte(CP_ACP, 0, wideChar, -1, 0, 0, 0, 0);
  42. multiByte = new char[iwstrLen + 1];
  43. memset(multiByte, 0, sizeof(char) * (iwstrLen + 1));
  44. WideCharToMultiByte(CP_ACP, 0, wideChar, -1, multiByte, iwstrLen, 0, 0);
  45. return multiByte;
  46. }
  47. char* CharConvert::GetMultiByteUTF8W(wchar_t* wideChar)
  48. {
  49. char* multiByte;
  50. int iwstrLen = WideCharToMultiByte(CP_UTF8, 0, wideChar, -1, 0, 0, 0, 0);
  51. multiByte = new char[iwstrLen + 1];
  52. memset(multiByte, 0, sizeof(char) * (iwstrLen + 1));
  53. WideCharToMultiByte(CP_UTF8, 0, wideChar, -1, multiByte, iwstrLen, 0, 0);
  54. return multiByte;
  55. }
  56. char* CharConvert::GetMultiByteW(wstring wideStr)
  57. {
  58. wchar_t* ptr = _wcsdup(wideStr.c_str());
  59. char* multiByte = GetMultiByteW(ptr);
  60. return multiByte;
  61. }
  62. std::wstring CharConvert::ReplaceSubStrW(wstring sourceStr, const wstring& oldSubStr, const wstring& newSubStr)
  63. {
  64. wstring strRet = sourceStr;
  65. size_t pos = 0;
  66. int l_count = 0;
  67. int count = -1;
  68. if (-1 == count) // replace all
  69. count = strRet.size();
  70. while ((pos = strRet.find(oldSubStr, pos)) != wstring::npos)
  71. {
  72. strRet.replace(pos, oldSubStr.size(), newSubStr);
  73. if (++l_count >= count) break;
  74. pos += newSubStr.size();
  75. }
  76. return strRet;
  77. }
  78. #pragma endregion
  79. #pragma endregion