Logo

Programming-Idioms

  • D
  • Smalltalk
  • Ada
  • Pascal

Idiom #274 Remove all white space characters

Create the string t from the string s, removing all the spaces, newlines, tabulations, etc.

uses RegExpr;
t := ReplaceRegExpr('\s', s, '');
  SetLength(t, Length(s));
  i := 0;
  for Ch in S do
    if (Ch > #32) then
    begin
      Inc(i);
      t[i] := Ch;
    end;
  SetLength(t, i);

Without regular expressions.
Probably faster then using consecutive calls to Delete()
Using SetLength is faster than repetitive string concatenation.
#include <iostream>
#include <string>
#include <algorithm>
auto t = s;
t.erase(std::ranges::remove_if(t, [](const char c) { return std::isspace(c); }).begin(),t.end()) ;

New implementation...