user3345195
user3345195

Reputation: 73

How can I replace a special characters in a given string with space or without space by using delphi

How can I replace special characters in a given string with spaces, or just remove it, by using Delphi? The following works in C#, but I don't know how to write it in Delphi.

public string RemoveSpecialChars(string str)
{
    string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";","_","(", ")", ":", "|", "[", "]" };

    for (int i = 0; i< chars.Lenght; i++)
    {
        if (str.Contains(chars[i]))
        {
            str = str.Replace(chars[i],"");
        }
    }
    return str;
}

Upvotes: 1

Views: 23883

Answers (4)

user3345195
user3345195

Reputation: 73

const
  InvalidChars  =
    [',','.','/','!','@','#','$','%','^','&','*','''','"',';','_','(',')',':','|','[',']'];

var
  // i, Count: Integer;
  str: String;

begin
  Writeln('please enter any Text');
  Readln(str);
  Writeln('The given Text is',str);
  Count := 0;
  for i := 1 to Length(str) do
    if (str[i] in InvalidChars) then
    begin
      str[i] := ' ';
      Write('');
    end;
  Writeln(str);
  Readln;
end.

Upvotes: -1

David Heffernan
David Heffernan

Reputation: 612914

I would write the function like this:

function RemoveSpecialChars(const str: string): string;
const
  InvalidChars : set of char =
    [',','.','/','!','@','#','$','%','^','&','*','''','"',';','_','(',')',':','|','[',']'];
var
  i, Count: Integer;
begin
  SetLength(Result, Length(str));
  Count := 0;
  for i := 1 to Length(str) do
    if not (str[i] in InvalidChars) then
    begin
      inc(Count);
      Result[Count] := str[i];
    end;
  SetLength(Result, Count);
end;

The function is pretty obvious when you see it written down. I prefer to try to avoid performing a large number of heap allocations which is why the code pre-allocates a buffer and then finalises its size at the end of the loop.

Upvotes: 9

Alex P.
Alex P.

Reputation: 3787

Actually there is StringReplace function in StrUtils unit which can be used like this:

uses StrUrils;

...

var
  a, b: string;
begin
  a := 'Google is awesome! I LOVE GOOGLE.';
  b := StringReplace(a, 'Google', 'Microsoft', [rfReplaceAll, rfIgnoreCase]); 
  // b will be 'Microsoft is awesome! I LOVE Microsoft'
end;

So you can write the code in almost the same way as you did in C# (instead of Contains you can use Pos function here). But I would recommend using HeartWare's approach since it should be a lot more efficient.

Upvotes: 5

HeartWare
HeartWare

Reputation: 8243

Try this one:

FUNCTION RemoveSpecialChars(CONST STR : STRING) : STRING;
  CONST
    InvalidChars : SET OF CHAR = [',','.','/','!','@','#','$','%','^','&','*','''','"',';','_','(',')',':','|','[',']'];

  VAR
    I : Cardinal;

  BEGIN
    Result:='';
    FOR I:=1 TO LENGTH(STR) DO
      IF NOT (STR[I] IN InvalidChars) THEN Result:=Result+STR[I]
  END;

Upvotes: 1

Related Questions