Search code examples
delphistringnon-ascii-characters

How can I replace \xA0 (or Non-ASCII) chars in a string to ' '?


I have an excel file with numerous Non-ASCII characters which I would like to replace with the space character.

This text is to be entered into a MySQL database, and it will not import with these characters in the strings. I get a HY000 Incorrect string value when trying to post the row.


Solution

  • If the set of Non-Ascii characters is fixed you could use:

    NewString := StringReplace(OriginalString,#1#4,' ',[rfReplaceAll])
    

    where #1#4 is the non-ascii characters you want to have replaced.

    Here is some docs on it's use.

    You could also do this.

    function StripNonAlpha(aInput : String) : String;
    var
     I : Integer;
    begin
     result := aInput;
     for I := 1 to length(result) do
     begin
       if not CharInSet(result[I],['A'..'Z','a'..'z']) then
          result[I] := ' ';
     end;
    end;
    

    Then you can change Set in CharInSet to the acceptable characters.