Logo

Programming-Idioms

  • Python
  • Pascal

Idiom #219 Replace multiple spaces with single space

Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.

uses sysutils;
  t := s;
  while Pos('  ',t) > 0 do
    t := StringReplace(t, '  ', ' ', [rfReplaceAll]);

Only removes double spaces.
StringReplace is not recursive, hence the loop.
var
  i, j: integer;
  t,s: string;
const
  whitespace = [#32,#13,#10,#9];
begin
  ....
  t := '';
  j := 0;
  setlength(t, length(s));
  for i := 1 to length(s) do
    if not ((s[i] in whitespace) and 
            ((i < length(s)) and (s[i+1] in whitespace))) then
    begin
      inc(j);
      t[j] := s[i];
    end;
  setlength(t,j);
end.

Removes all double whitespace.
Using setlength twice and accessing individual characters of the result is faster than adding characters one at a time.
More elaborate, but faster than the RegEx and StringReplace solutions.
regexpr
  t := ReplaceRegExpr('\s+',s,' ',False);

Yes, you can do it with a RegEx as well.
Removes all double whitespace.
t: str = " ".join(s.split())

Splits s into a list based on whitespace, then joins them together again
import re
t = re.sub(' +', ' ', s)

Only replaces spaces.
from re import split
t = ' '.join(split(' {2,}', s))
from re import split
t = ' '.join(split(r'\s{2,}', s))
(def t (clojure.string/replace s #"\s+" " "))

New implementation...