Logo

Programming-Idioms

  • Python
  • JS
  • PHP

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.

#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());
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(r'\s{2,}', s))
from re import split
t = ' '.join(split(' {2,}', s))
let t = s.replace(/\s+/g, ' ');

This replaces any sequence of whitespaces with a single space.
let t = s.replaceAll(/ {2,}/g, '')
let t = s.replaceAll(/\s{2,}/g, '')
$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
(def t (clojure.string/replace s #"\s+" " "))

New implementation...