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个函数要配套使用!

原文地址:https://www.cnblogs.com/zhangzhifeng/p/3299680.html