• 自己写unicode转换ascii码,wchar*到char*


    对于ascii码的char事实上就是unicode码wchar的首个字节码,

    如wchar[20] = "qqqq"; 在内存中排码事实上是char的'q' ''这类。因此我们假设自己写unicode码转换为ascii的char,仅仅须要取其首字节就可以,例如以下本人写了一个wchar到char的转换的函数。

    因为代码简单,加上了内存泄露測试方式。

     

    #include <stdio.h>
    #ifdef _DEBUG
    #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
    #else
    #define DEBUG_CLIENTBLOCK
    #endif
    
    #define _CRTDBG_MAP_ALLOC
    #include <stdlib.h>
    #include <crtdbg.h>
    #include <tchar.h>
    #include <Windows.h>
    #ifdef _DEBUG
    #define new DEBUG_CLIENTBLOCK
    #endif
    
    char* UnicodeToMultibyte(WCHAR *wStr)
    {
    
    	if (NULL != wStr)
    	{
    		int nLen = wcslen(wStr);
    		char *pStr = new char[nLen + 1];
    		int i = 0;
    		for (; i < nLen; ++i)
    		{
    			(pStr)[i] = (char)*(wStr + i);
    		}
    		(pStr)[i] = '';
    		printf("%s
    ", pStr);
    		return pStr;
    	}
    	return NULL;
    }
    int main()
    {
    	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    
    	/*char *str = new char[100];*/
    	WCHAR wStr[250] = L"qqqqqqqqqqqqq";
    	char szTemp[250] = _T("wwwwwwwwwwwww");
    	char* pTemp = UnicodeToMultibyte(wStr);
    	strcpy(szTemp, pTemp);
    	delete pTemp;		//注意,小心内存泄露
    	printf("%s
    ", szTemp);
    
    	return 0;
    
    }


    当然也能够通过windows的转换函数,这个msdn上有具体解释就不解释啦

    char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)  
    {  
    	LPSTR pszOut = NULL;  
    	if (lpwszStrIn != NULL)  
    	{  
    		int nInputStrLen = wcslen (lpwszStrIn);  
    
    		// Double NULL Termination  
    		int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;  
    		pszOut = new char [nOutputStrLen];  
    
    		if (pszOut)  
    		{  
    			memset (pszOut, 0x00, nOutputStrLen);  
    			WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);  
    		}  
    	}  
    	return pszOut;  
    }


     

  • 相关阅读:
    219. Contains Duplicate II
    189. Rotate Array
    169. Majority Element
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    119. Pascal's Triangle II
    118. Pascal's Triangle
    88. Merge Sorted Array
    53. Maximum Subarray
    CodeForces 359D Pair of Numbers (暴力)
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6943626.html
Copyright © 2020-2023  润新知