Search code examples
ddmdphobos

Remove white space characters from a char[] array in D


What is the recomended way to remove white space from a char[] in D. for example using dmd 2.057 I have,

import std.stdio;
import std.string; 
import std.algorithm;

char[] line;

int main(){
  line = r"this is a     line with spaces   "; 
  line = removechars(line," "); 
  writeln(line);
  return 0;
}

On compile, this will generate this error:

Error: cannot implicitly convert expression ("this is a     line with spaces   ") of type string to char[]
    Error: template std.string.removechars(S) if (isSomeString!(S)) does not match any function template declaration
    Error: template std.string.removechars(S) if (isSomeString!(S)) cannot deduce template function from argument types !()(char[],string)

On doing some google search, i find that a similar error had been reported as a bug and had been filed in june 2011, but not sure whether it was was referring to the same thing or a different issue.

In general, what is the approach recommended to remove certain characters from a string and maintating the order of characters from the previous array of chars?

In this case return

assert(line == "thisisalinewithspaces")

after removing whitespace characters


Solution

  • removechars accepts all string types (char[], wchar[], dchar[], string, wstring and dstring), but the second argument has to be the same type as the first. So if you pass a char[] as first arg, the second arg also has to be a char[]. You are, however, passing a string: " "

    A simple solution would be to duplicate the string to a char[]: " ".dup

    removechars(line, " ".dup)

    This also works:

    removechars(line, ['\x20'])