Changing special characters in a Delphi array

Some string that I get is encoded by UTF-8 and contains some special characters like Å, Ä ', Ä, etc. I use StringReplace() to convert it to plain text, but I can only convert one type of character. Since PHP also has a function for replacing strings, as shown here: how to replace special characters with those on which they are based on PHP? but supports arrays:

 <?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.' ?> 

How can I do this in Delphi? StringReplace does not support arrays.

+6
source share
2 answers
 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; 

If you are concerned about all unnecessary heap allocations caused by StringReplace , you can write it like this:

 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; 

Name it as follows:

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

Getting rid of your emphasis is called Normalization .

Since you use Unicode, you not only want to normalize a short list of accented characters in your question. In fact, you are looking for a Unicode Normalization Form D (NFD) or KD (NFKD), which you can do on Windows and, of course, Delphi.

This answer should help you move to the theoretical side.

This Delphi code and this answer should make you start the implementation.

+6
source

Source: https://habr.com/ru/post/892156/


All Articles