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

一世执手 提交于 2019-12-14 02:42:14

问题


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;
}

回答1:


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.




回答2:


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.




回答3:


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;



回答4:


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.


来源:https://stackoverflow.com/questions/21979184/how-can-i-replace-a-special-characters-in-a-given-string-with-space-or-without-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!