我想从字符串值中删除空格。例如,
sString := 'Hello my name is Bob
应变为 sString := 'HellomynameisBob
。
我尝试使用 while 循环:
iPos := pos(' ', sString);
while iPos > 0 do
Delete(sString,iPos,1);
但是程序就冻结了。
程序冻结,因为您从未在循环中增加
iPos
。
最简单的解决方案是使用
SysUtils
- StringReplace
(reference) 中声明的 Delphi 函数,如下所示:
newStr := StringReplace(srcString, ' ', '', [rfReplaceAll]); //Remove spaces
iPos := pos(' ', sString);
while iPos > 0 do begin
Delete(sString,iPos,1);
iPos := pos(' ', sString);
end;
虽然@Kromster 是对的,但这并不是解决这个问题的正确方法。 您应该使用 StringReplace 函数,在其中传递
sString
、要替换的字符、要替换的字符以及一些内置标志。所以你的代码应该如下所示:
sString := 'Hello my name is Bob;
newString := stringReplace(sString, ' ', '', [rfReplaceAll, rfIgnoreCase]);
newString
现在应该返回 'HellomynameisBob'
。
使用此代码:
使用正则表达式;
var
Text: string;
RegEx: TRegEx;
...
Text := '1 2 3';
RegEx := TRegEx.Create('(\s)+', [roIgnoreCase]);
Text := RegEx.Replace(Text , ' ');