Logo

Programming-Idioms

  • Lua
  • Clojure

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.

(def t (clojure.string/replace s #"\s+" " "))
local t = s:gsub("%s+", " ")

string.gsub(s, "%s+", " ") can be used instead of s:gsub("%s+", " ")
#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());

New implementation...