Reputation: 199
I want to delete spaces from a string value. For example, sString := 'Hello my name is Bob
should become sString := 'HellomynameisBob
.
I tried using the while loop:
iPos := pos(' ', sString);
while iPos > 0 do
Delete(sString,iPos,1);
but the program just freezes.
Upvotes: 2
Views: 15813
Reputation: 57
Use this code:
uses RegularExpressions;
var
Text: string;
RegEx: TRegEx;
...
Text := '1 2 3';
RegEx := TRegEx.Create('(\s)+', [roIgnoreCase]);
Text := RegEx.Replace(Text , ' ');
Upvotes: 0
Reputation: 302
While @Kromster is right, this far not the right approach to deal with this.
You should use the StringReplace Function where you pass sString
, the character to replace, the character to replace with, and some built-in flags. so your code should look like this:
sString := 'Hello my name is Bob;
newString := stringReplace(sString, ' ', '', [rfReplaceAll, rfIgnoreCase]);
newString
should now return 'HellomynameisBob'
.
Upvotes: 1
Reputation: 7397
The program freezes because you never increment the iPos
in your loop.
Simplest solution is to use Delphi function declared in SysUtils
- StringReplace
(reference) like so:
newStr := StringReplace(srcString, ' ', '', [rfReplaceAll]); //Remove spaces
Upvotes: 23
Reputation: 124
iPos := pos(' ', sString);
while iPos > 0 do begin
Delete(sString,iPos,1);
iPos := pos(' ', sString);
end;
Upvotes: 4