Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #219 Replace multiple spaces with single space

Create 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.

import re
t = re.sub(' +', ' ', s)
import "regexp"
whitespaces := regexp.MustCompile(`\s+`)
t := whitespaces.ReplaceAllString(s, " ")
let t = s.replace(/\s+/g, ' ');
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.
sysutils
  t := s;
  while Pos('  ',t) > 0 do
    t := StringReplace(t, '  ', ' ', [rfReplaceAll]);
regexpr
  t := ReplaceRegExpr('\s+',s,' ',False);

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms