如何使用delphi用空格或无空格替换给定字符串中的特殊字符

use*_*195 1 delphi delphi-7

如何用空格替换给定字符串中的特殊字符,或者只是删除它,使用Delphi?以下适用于C#,但我不知道如何在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;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 8

我会写这样的函数:

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;
Run Code Online (Sandbox Code Playgroud)

当你看到它写下来时,这个功能非常明显.我更愿意尝试避免执行大量的堆分配,这就是代码预先分配缓冲区然后在循环结束时最终确定其大小的原因.


Ale*_* P. 5

实际上 StrUtils 单元中有StringReplace函数,可以这样使用:

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;
Run Code Online (Sandbox Code Playgroud)

因此,您可以用与 C# 中几乎相同的方式编写代码(您可以在此处使用 Pos 函数,而不是 Contains)。但我建议使用HeartWare的方法,因为它应该更有效。