Logo

Programming-Idioms

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.
Implementation
VB

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another VB implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
let t = s.replace(/\s+/g, ' ');
import "regexp"
whitespaces := regexp.MustCompile(`\s+`)
t := whitespaces.ReplaceAllString(s, " ")
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.
uses sysutils;
  t := s;
  while Pos('  ',t) > 0 do
    t := StringReplace(t, '  ', ' ', [rfReplaceAll]);
regexpr
  t := ReplaceRegExpr('\s+',s,' ',False);
import re
t = re.sub(' +', ' ', s)
t = s.squeeze(" ")
my $t = $s;
$t =~ s/ +/ /g;
my $t = $s;
$t =~ s/\s+/ /g;
def t = s.replaceAll(/\s+/, ' ')
use regex::Regex;
let re = Regex::new(r"\s+").unwrap();
let t = re.replace_all(s, " ");
$t = preg_replace('/\s+/', ' ', $s);
$t = $s;
do $t = str_replace('  ', ' ', $t, $count); while($count);
local t = s:gsub("%s+", " ")
using System.Text.RegularExpressions;
string t = Regex.Replace(s, " +", " ");
using System.Text.RegularExpressions;
string t = Regex.Replace(s, @"\s+", " ");
String t = s.replaceAll(" +", " ");
String t = s.replaceAll("\\s+", " ");
Imports System.Text.RegularExpressions
Dim t As String = Regex.Replace(s, " +", " ")
singleSpace(Text) ->
        singleSpace(0, Text).

singleSpace(_, []) -> [];
singleSpace(32, [32 | Rest]) ->
        singleSpace(32, Rest);
singleSpace(32, [Ch | Rest]) ->
        [Ch] ++ singleSpace(Ch,  Rest);
singleSpace(Last, [Ch | Rest]) ->
                [Ch] ++ singleSpace(Ch, Rest).


%%singleSpace("this is  a      text  with        multiple spaces").
var t = s.replaceAll(RegExp(r"\s+"), " ");
(def t (clojure.string/replace s #"\s+" " "))
t: str = " ".join(s.split())
t= unwords $ words s
(defun words (str)
  (if (equalp str "") nil 
      (let ((p (position #\Space str )))
    (cond ((null p) (list str))
          ((zerop p ) (words (subseq str 1)))
          (T (cons (subseq str 0 p) (words (subseq str (+ 1 p ))))))))) 

(setf s " aa  bbb  cc1 ")

 (let ((ws (words s )))
   (setf t (car ws))
   (dolist (w (cdr ws ))
     (setf t (concatenate 'string t " " w ))))
 (print t)