2012-06-17 118 views
2

我有一個char[]字符。我想刪除空格。我的方法:如何從char []中刪除元素?

import std.algorithm; 
import std.ascii; 
// ... 
digits = remove!"isWhite(digits)"(digits); 

但是,這並不工作:

c:\dmd2\windows\bin\..\..\src\phobos\std\functional.d(70): Error: static assert "Bad unary function: isWhite(digits) for type dchar" 

如何從一個char[]刪除所有的空格?

回答

4
import std.algorithm; 
import std.stdio; 
import std.uni; 
import std.array; 

void main() { 

    char[] s = "12 abc fg ".dup; 

    writeln(array(s.filter!(x => !x.isWhite))); 
} 

array需要擺脫的filterResult -returntype。但是如果你想和Ranges一起工作,你不必這樣做。

+0

謝謝。 'filter'也引起了我的注意,但我認爲'remove'是正確的選擇。 –

+0

我選擇了過濾器,因爲它是一個非常強大的工具,與新的lambda表達式結合在一起(它與UFCS看起來非常整齊)。例如。你可以一次性移除所有的空格和一組特殊的字符和所有數字以及字符「ABF」。 – dav1d

2

更經濟的版本(即不進行內存分配)就是用這樣的std.algorithm.remove(未經測試):

s = remove!isWhite(s); 

你最初的使用移除用於拉姆達整個嘗試字符串,但它只需要一個字符。

+0

我只能得到這個工作,如果我將字符串轉換爲dchar []:s = remove!isWhite(to!(dchar [])(s)); – fwend