简体   繁体   English

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

[英]How do I delete spaces from a string?

I want to delete spaces from a string value.我想从字符串值中删除空格。 For example, sString := 'Hello my name is Bob should become sString := 'HellomynameisBob .例如, sString := 'Hello my name is Bob应该变成sString := 'HellomynameisBob

I tried using the while loop:我尝试使用 while 循环:

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

but the program just freezes.但程序只是冻结。

The program freezes because you never increment the iPos in your loop.程序冻结是因为您从不增加循环中的iPos

Simplest solution is to use Delphi function declared in SysUtils - StringReplace ( reference ) like so:最简单的解决方案是使用在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;

While @Kromster is right, this far not the right approach to deal with this.虽然@Kromster 是对的,但这远不是处理这个问题的正确方法。 You should use the StringReplace Function where you pass sString , the character to replace, the character to replace with, and some built-in flags.您应该在传递sString地方使用 StringReplace 函数、要替换的字符、要替换的字符以及一些内置标志。 so your code should look like this:所以你的代码应该是这样的:

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

newString should now return 'HellomynameisBob' . newString现在应该回到'HellomynameisBob'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM