牛骨文教育服务平台(让学习变的简单)
博文笔记

Delphi String 与wideString 的完美转换

创建时间:2016-08-30 投稿人: 浏览次数:2956

Delphi String 与wideString 的完美转换

一般来说,String与widestring 的转换是系统自动进行的,但是,考虑如下字符串 s:=#2+#3+#0+#10+#0+#1+#164+#59;,显然S的长度为8,然后执行如下代码 var S,S2:string; I: Integer; WS:widestring; begin s:=#2+#3+#0+#10+#0+#1+#164+#59; showmessage(inttostr(Length(S))); //显示为8,正常 WS := S; showmessage(inttostr(Length(WS))); //显示为7。。。 S := WS; showmessage(inttostr(Length(S))); //显示为7。。。少了一位 造成这点的原因就在于,当字符的ascii码大于127的时候,widestring判断它为一个双字节的词(比如中文字符之类的) 完美转换的方法如下: //string to widestring
setlength(WS,Length(S));
for I := 1 to length(S) do // Iterate
begin WS[I]:= widechar(S[I]);
end; // for
//widestring to string
setlength(S2,Length(WS));
for I := 1 to length(WS) do // Iterate
begin S2[I]:= char(WS[I]);
end; // for
showmessage(inttostr(Length(S2)));
if S=S2 then showmessage("OK");
注意的是,s=s2,但是 s<>ws 因为现在很多COM接口什么的都是Widestring类型的,假如要传递用16进制写的字符串的话,容易造成丢失字节,用这种办法就可以解决这个问题了,但是要记得是,这2个函数要配套使用!

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。