Logo

Programming-Idioms

  • Ruby
  • Java

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.

using System.Text.RegularExpressions;
string t = Regex.Replace(s, @"\s+", " ");

Replaces consecutive whitespace with a space. Verbatim string used to avoid escaping backslash.
using System.Text.RegularExpressions;
string t = Regex.Replace(s, " +", " ");

Replaces consecutive spaces with a single space.
t = s.squeeze(" ")

Just spaces.
import static java.lang.String.join;
String t = join(" ", s.split(" +", -1));
String t = s.replaceAll(" {2,}", " ");
String t = s.replaceAll("\\s+", " ");

Replaces consecutive whitespace with a space.
String t = s.replaceAll(" +", " ");

Replaces consecutive spaces with a single space.
(def t (clojure.string/replace s #"\s+" " "))

New implementation...