如何从字符串中删除空格?

问题描述 投票:0回答:4

我想从字符串值中删除空格。例如,

sString := 'Hello my name is Bob
应变为
sString := 'HellomynameisBob

我尝试使用 while 循环:

iPos := pos(' ', sString);
while iPos > 0 do
Delete(sString,iPos,1);

但是程序就冻结了。

string delphi
4个回答
21
投票

程序冻结,因为您从未在循环中增加

iPos

最简单的解决方案是使用

SysUtils
-
StringReplace
(reference) 中声明的 Delphi 函数,如下所示:

newStr := StringReplace(srcString, ' ', '', [rfReplaceAll]); //Remove spaces

4
投票
iPos := pos(' ', sString);
while iPos > 0 do begin
  Delete(sString,iPos,1);
  iPos := pos(' ', sString);
end;

1
投票

虽然@Kromster 是对的,但这并不是解决这个问题的正确方法。 您应该使用 StringReplace 函数,在其中传递

sString
、要替换的字符、要替换的字符以及一些内置标志。所以你的代码应该如下所示:

sString := 'Hello my name is Bob;
newString := stringReplace(sString, ' ', '', [rfReplaceAll, rfIgnoreCase]);

newString
现在应该返回
'HellomynameisBob'


0
投票

使用此代码:

使用正则表达式;

var
  Text: string;
  RegEx: TRegEx;
...
Text := '1          2      3';
RegEx := TRegEx.Create('(\s)+', [roIgnoreCase]);
Text := RegEx.Replace(Text , ' ');
© www.soinside.com 2019 - 2024. All rights reserved.