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

前端之家收集整理的这篇文章主要介绍了数组 – 更改数组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.f2er.com/delphi/101270.html

猜你在找的Delphi相关文章