微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组 – 更改数组Delphi中的特殊字符

我得到的一些字符串是UTF-8编码,并包含一些特殊字符,如
Å¡,Ä’,Ä等.我使用StringReplace()将其转换为一些普通文本,但我只能转换一种类型的字符.因为 PHP还有一个替换字符串的功能,如下所示: how to replace special characters with the ones they’re based on in PHP?,但它支持数组:
<?PHP
  $vOriginalString = "¿Dónde está el niño que vive aquí? En el témpano o en el iglú. ÁFRICA,MÉXICO,ÍNDICE,CANCIÓN y NÚMERO.";

  $vSomeSpecialChars = array("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","Ñ");
  $vReplacementChars = array("a","e","i","o","u","A","E","I","O","U","n","N");

  $vReplacedString = str_replace($vSomeSpecialChars,$vReplacementChars,$vOriginalString);

  echo $vReplacedString; // outputs '¿Donde esta el nino que vive aqui? En el tempano o en el iglu. AFRICA,MEXICO,INDICE,CANCION y NUMERO.'
?>

我怎么能在Delphi中这样做? StringReplace不支持数组.

解决方法

function str_replace(const oldChars,newChars: array of Char; const str: string): string;
var
  i: Integer;
begin
  Assert(Length(oldChars)=Length(newChars));
  Result := str;
  for i := 0 to high(oldChars) do
    Result := StringReplace(Result,oldChars[i],newChars[i],[rfReplaceAll])
end;

如果您担心StringReplace引起的所有不必要的堆分配,那么您可以这样写:

function str_replace(const oldChars,newChars: array of Char; const str: string): string;
var
  i,j: Integer;
begin
  Assert(Length(oldChars)=Length(newChars));
  Result := str;
  for i := 1 to Length(Result) do
    for j := 0 to high(oldChars) do
      if Result[i]=oldChars[j] then
      begin
        Result[i] := newChars[j];
        break;
      end;
end;

像这样称呼它:

newStr := str_replace(
  ['á','é','í'],['a','e','i'],oldStr
);

原文地址:https://www.jb51.cc/delphi/101270.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐