Logo

Programming-Idioms

  • PHP
  • C++
  • 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.

regexpr
  t := ReplaceRegExpr('\s+',s,' ',False);

Yes, you can do it with a RegEx as well.
Removes all double whitespace.
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.
$t = $s;
do $t = str_replace('  ', ' ', $t, $count); while($count);

only spaces are handled

might not be very efficient, but does not use regexes
$t = preg_replace('/\s+/', ' ', $s);

replaces all whitespace
#include <iostream>
#include <string>
#include <algorithm>
auto t = s;
t.erase(std::ranges::unique(t, 
  [](char const &lhs,char const &rhs)
  { return lhs == rhs && ::std::iswspace(lhs); }
).begin(), t.end());
(def t (clojure.string/replace s #"\s+" " "))

New implementation...