我正在尝试替换html代码中的一些通配符以通过邮件发送。 问题是,当我尝试将通配符'España$ country $'替换为字符串'España'时,结果将是'EspañaEspa?a'。我之前在Delphi 7中也遇到过同样的问题,我通过使用函数'UTF8Encode('España')'解决了该问题,但在Delphi 10上却不起作用。
我尝试使用'España','UTF8Encode('España')'和'AnsiToUTF8('España')'。我还尝试使用ReplaceStr和ReplaceText更改功能StringReplace,结果相同。
......
var htmlText : TStringList;
......
htmlText := TStringList.Create;
htmlText.LoadFromFile('path.html');
htmlText.StringReplace(htmlText.Text, '$country$', UTF8Encode('España'), [rfReplaceAll]);
htmlText.SaveToFile('anotherpath.html');
......
此“ stringreplace”与“ utf8encode”一起在Delphi7中运行良好,显示为'España',但在delphi 10中却不能,在那里您可以在anotherpath.html中读取'Espa?a'。
答案 0 :(得分:1)
Delphi 7 string
类型(因此TStrings
)不支持Unicode。这就是为什么您需要使用UTF8Encode
。
从Delphi 2009开始,支持Unicode,并且string
映射到UnicodeString
,TStrings
是此类字符串的集合。请注意,UnicodeString
在内部被编码为UTF-16,但这不是您在此处需要关注的细节。
由于您现在使用的是支持Unicode的Delphi,因此您的代码可以更加简单。您现在可以这样写:
htmlText.Text := StringReplace(htmlText.Text, '$country$', 'España', [rfReplaceAll]);
请注意,如果希望在保存文件时将其编码为UTF-8,则需要在保存时指定该文件。像这样:
htmlText.SaveToFile('anotherpath.html', TEncoding.UTF8);
如果文件不包含UTF-8 BOM,则在加载文件时可能还需要指定编码:
htmlText.LoadFromFile('path.html', TEncoding.UTF8);