Logo

Programming-Idioms

History of Idiom 219 > diff from v3 to v4

Edit summary for version 4 by Bart:
New Pascal implementation by user [Bart]

Version 3

2020-02-28, 09:26:39

Version 4

2020-02-29, 15:31:18

Idiom #219 Replace multiple spaces with single space

Create 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.

Idiom #219 Replace multiple spaces with single space

Create 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.

Extra Keywords
collapse repeated
Extra Keywords
collapse repeated
Code
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.
Comments bubble
Removes all double whitespace.
Using setlength twice and accessing individual characters of the result is faster than adding characters one at a time.