我必须将一些 UTF-8 编码的文本文件导入到我的 C++Builder 5 程序中。是否有任何组件或代码示例可以实现这一点?
Riho
问问题
2910 次
4 回答
2
这是一个更以 VCL 为中心的方法:
UTF8String utf8 = "...";
WideString utf16;
AnsiString latin1;
int len = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), utf8.Length(), NULL, 0);
utf16.SetLength(len);
::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), utf8.Length(), utf16.c_bstr(), len);
len = ::WideCharToMultiByte(1252, 0, utf16.c_bstr(), utf16.Length(), NULL, 0, NULL, NULL);
latin1.SetLength(len);
::WideCharToMultiByte(1252, 0, utf16.c_bstr(), utf16.Length(), latin1.c_str(), len, NULL, NULL);
如果升级到 CB2009,可以将其简化为:
UTF8String utf8 = "...";
AnsiString<1252> latin1 = utf8;
于 2009-07-14T00:54:42.617 回答
0
由于周末没有人工作,我必须自己回答:)
String Utf8ToWinLatin1(char* aData, char* aValue)
{
int i=0;
for(int j=0;j<strlen(aData);)
{ int val=aData[j];
int c=(unsigned char)aData[j];
if(c<=127)
{ aValue[i]=c;
j+=1;
i++;
}
else if(c>=192 && c<=223)
{
aValue[i]=(c-192)*64 + (aData[j+1]-128);
i++;
j+=2;
}
else if(c>=224 && c<=239)
{
aValue[i]=( c-224)*4096 + (aData[j+1]-128)*64 + (aData[j+2]-128);
i++;
j+=3;
}
else if(c>=240 && c<=247)
{
aValue[i]=(c-240)*262144 + (aData[j+1]-128)*4096 + (aData[j+2]-128)*64 + (aData[j+3]-128);
i++;
j+=4;
}
else if(c>=248 && c<=251)
{
aValue[i]=(c-248)*16777216 + (aData[j+1]-128)*262144+ (aData[j+2]-128)*4096 + (aData[j+3]-128)*64 + (aData[j+4]-128);
i++;
j+=5;
}
else
j+=1;
}
return aValue;
}
于 2009-01-24T11:59:11.787 回答
-1
您的问题没有具体说明您要转换为哪个字符集。如果您只想要基本的 7 位 ASCII 字符集,则丢弃值高于 127 的每个字符都可以。
如果您想转换为 8 位字符集,例如 latin1,您将不得不费尽心思。
于 2009-01-24T12:38:34.220 回答