Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove space around a character?

Tags:

string

delphi

Say I have the following string:

s := 'This , is,       the Delphi  ,    World!';

I would like the following output:

Result := 'This,is,the Delphi,World!';

Basically I need a routine that strips ALL occurrences of spaces ONLY if they appears before or after the comma char (which is my delimiter), leaving intact spaces between other words.

Any help is much appreciated.

What do you think of this solution?

function RemoveSpacesAroundDelimiter(var aString: string; aDelimiter:
    string): string;
begin
  while AnsiContainsText(aString, aDelimiter + ' ') do
    begin
    aString := StringReplace(aString, ', ', aDelimiter, [rfReplaceAll, rfIgnoreCase]);
    end;

  while AnsiContainsText(aString, ' ' + aDelimiter) do
    begin
    aString := StringReplace(aString, ' ' + aDelimiter, aDelimiter, [rfReplaceAll, rfIgnoreCase]);
    end;

  Result := aString;
end;

thanks

fabio

like image 397
Fabio Vitale Avatar asked Nov 09 '11 14:11

Fabio Vitale


People also ask

How do I remove spaces from a char string?

Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.

What text removes spaces?

The TRIM function will remove all the space characters at the start and end of a text string.

Which function removes unwanted space between characters?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.


1 Answers

Sounds like a task for TStringList.

function UltraTrim(Value: string): string;
var
  sl: TStringList;
  i: Integer;
begin
  sl := TStringList.Create;
  try
    // Prevent the stringlist from using spaces as delimiters too.
    sl.StrictDelimiter := True;

    // Set the comma separated text.
    sl.CommaText := Value;

    // Trim each item.
    for i := 0 to sl.Count -1 do
      sl[i] := Trim(sl[i]);

    // Concat back to comma separated string.
    Result := sl.CommaText;
  finally
    sl.Free;
  end;

end;
like image 81
GolezTrol Avatar answered Oct 15 '22 15:10

GolezTrol