如何通过使用delphi替换给定字符串中带空格或不带空格的特殊字符 [英] How can I replace a special characters in a given string with space or without space by using delphi
本文介绍了如何通过使用delphi替换给定字符串中带空格或不带空格的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Delphi将给定字符串中的特殊字符替换为空格或将其删除?以下代码在C#中有效,但我不知道如何在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;
}
推荐答案
我会这样写函数:
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.
这篇关于如何通过使用delphi替换给定字符串中带空格或不带空格的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文