我正在慢慢地将现有代码转换为Delphi 2010,并阅读Embarcaedro网站以及MarcoCantú白皮书中的几篇文章。将函数转换为delphi 2009/2010(unicode)
仍然有一些事情我没有理解,所以这里有两个函数来举例说明我的问题:
function RemoveSpace(InStr: string): string;
var
Ans : string;
I : Word;
L : Word;
TestChar: string[1];
begin
Ans := '';
L := Length(InStr);
if L > 0 then
begin
for I := 1 to L do
begin
TestChar := Copy(InStr, I, 1);
if TestChar <> ' ' then Ans := Ans + TestChar;
end;
end;
RemoveSpace := Ans;
end;
function ReplaceStr(const S, Srch, Replace: string): string;
var
I: Integer;
Source: string;
begin
Source := S;
Result := '';
repeat
I := Pos(Srch, Source);
if I > 0 then begin
Result := Result + Copy(Source, 1, I - 1) + Replace;
Source := Copy(Source, I + Length(Srch), MaxInt);
end
else Result := Result + Source;
until I <= 0;
end;
对于RemoveSpace功能,如果没有Unicode字符传递(“AA BB”例如), 一切都很好。现在,如果我传递文本“ab cd”,那么该函数不能按预期工作(我将ab ?? cd作为输出)。
如何解释字符串上可能的Unicode字符?使用Length(InStr)显然是不正确的以及Copy(InStr,I,1)。
转换此代码的最佳方式是什么,以便它解释unicode字符?
谢谢!
咦?字作为字符串的长度和索引的类型?从Delphi 3开始生产代码?除了Aldo的解决方案,我建议你确保你的代码编译时没有警告(甚至更好:没有提示)。 – 2009-10-08 09:18:02
Jeroen,我在这段代码中看不到会产生警告或提示。为Word分配一个整数不会生成一条消息;不过,它可能会导致长度超过65535个字符的范围检查错误。对于永远不能为负数的变量(如字符串长度和索引),使用无符号类型是很常见的,而在Delphi 3中,Word是可用的最大无符号类型。 (真正的无符号红衣主教只能排在德尔福4,引进的Int64的。) – 2009-10-08 16:10:41