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個函數要配套使用!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM