This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
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.
- Clojure
- C++
- C#
- C#
- Dart
- Erlang
- Go
- Groovy
- Haskell
- JS
- JS
- JS
- Java
- Java
- Java
- Java
- Lisp
- Lua
- PHP
- PHP
- Pascal
- Pascal
- Pascal
- Perl
- Perl
- Python
- Python
- Python
- Python
- Ruby
- Rust
- VB
- VB
auto t = s;
t.erase(std::ranges::unique(t,
[](char const &lhs,char const &rhs)
{ return lhs == rhs && ::std::iswspace(lhs); }
).begin(), t.end());
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").
pure erlang implementation
(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)
The words function is https://programming-idioms.org/idiom/49/split-a-space-separated-string/6327/lisp
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.
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.
programming-idioms.org