Delphi – convert function to delphi 2009/2010 (unicode)

delphidelphi-2009delphi-2010unicode

I'm slowly converting my existing code into Delphi 2010 and read several of the articles on Embarcaedro web site as well as Marco Cantú whitepaper.

There are still some things I haven't understood, so here are two functions to exemplify my question:

function RemoveSpace(InStr: string): string;
var
  Ans     : string;
  I       : Word;
  L       : Word;
  TestChar: string[1];
begin
  Ans := '';
  L := Length(InStr);
  if L > 0 then
  begin
    for I := 1 to L do
    begin
      TestChar := Copy(InStr, I, 1);
      if TestChar <> ' ' then Ans := Ans + TestChar;
    end;
  end;
  RemoveSpace := Ans;
end;

function ReplaceStr(const S, Srch, Replace: string): string;
var
  I: Integer;
  Source: string;
begin
  Source := S;
  Result := '';
  repeat
    I := Pos(Srch, Source);
    if I > 0 then begin
      Result := Result + Copy(Source, 1, I - 1) + Replace;
      Source := Copy(Source, I + Length(Srch), MaxInt);
    end
    else Result := Result + Source;
  until I <= 0;
end;

For the RemoveSpace function, if no unicode character is passed ('aa bb' for example), all is well. Now if I pass the text 'ab cd' then the function doesn't work as expected (I get ab??cd as the output).

How can I account for possible unicode characters on a string? using Length(InStr) is obviously incorrect as well as Copy(InStr, I, 1).

What's the best way of converting this code so that it accounts for unicode characters?

Thanks!

Best Answer

If those were your REAL functions and you're just trying to get em working then :

function RemoveSpace(const InStr: string): string;
begin
  Result := StringReplace(InStr, ' ', '', [rfReplaceAll]); 
end;

function ReplaceStr(const S, Srch, Replace: string): string;
begin
  Result := StringReplace(S, Srch, Replace, [rfReplaceAll, rfIgnoreCase]); 
end;