69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <malloc.h>
#include <windows.h>
#include <locale.h>
//---------------------------------------------------------------------------
// 函数说明 : 按照UNICODE方式截取字符串指定位置左面的字符串
// 输入参数 : char* szAscii 被截取指定的字符串
// 输入参数 : int nPos 截取的位置
// 输入参数 : char* szSave 截取后保存到得字符串
// 返 回 值 : BOOL 是否成功截取
// 作者信息 : 自由人生 2009-6-10 9:30:55
//---------------------------------------------------------------------------
BOOL StrLeftW(char* szAscii, int nPos, char* szSave)
{
int nLenght;
wchar_t* szWText;
// 保存截取后的字符串是否有足够的空间
if (nPos > (int)strlen(szSave))
return FALSE;
// 为宽字符串创建内存空间
nLenght = strlen(szAscii)+1;
szWText = (wchar_t*)malloc(nLenght*sizeof(wchar_t));
if (szWText == NULL)
return FALSE;
// 将被截取的字符串转换为宽字符集
MultiByteToWideChar(CP_ACP, 0, szAscii, -1, szWText, nLenght);
szWText[nPos] = L'\0';
// 将截取后的宽字符集转换保存到指定的多字符集字符串中
nLenght = WideCharToMultiByte(CP_ACP, 0, szWText, -1, szSave, nPos*sizeof(wchar_t), NULL, FALSE);
szSave[nLenght] ='\0';
// 释放空间
free(szWText);
szWText = NULL;
return TRUE;
}
int main()
{
char* szAsc = "我A我家";
char szGetLeft[5];
setlocale(LC_CTYPE, "");
if (StrLeftW(szAsc, 3, szGetLeft))
printf("%s\n", szGetLeft);
else
printf("error!\n");
return 0;
}
#include <stdio.h>
#include <locale.h>
int main()
{
wchar_t s[5] = L"我A我家";
setlocale(LC_CTYPE, "");
putwchar(s[0]);
putwchar(s[1]);
putchar("\n");
return 0;
}
int main()
{
const char *src="我A我家";
char dst[5];
int i=0;
memcpy(dst, src, 4);
dst[4]='\0';
for(i=0; i<4; )
{
if( dst[i]<0 ) /* 汉字,两个字节 */
i += 2;
else /* ASCII码字符 */
i ++;
}
if(i==5) /* 最后一个字节是半个汉字,截断 */
dst[3] = '\0';
printf("%s\n", dst);
return 0;
}