我想用D编程语言分割一个字符串,这样空字符串的元素就不会被计算在内。
示例:
输入:
This is a string
[注意is
和a
之间有3个空格]
输出:
[This, is, a, string]
问题
如果我使用
std.array.split
[链接 here] 函数并以 " "
(空格)作为分隔符,那么我会得到:["This", "is", " ", "a", "string"]
。请参阅 "is"
和 "a"
之间的空白元素。
我当前的解决方案
output = input.split(" ").filter!(l => !l.strip().empty).array;
注意,如果将多个连续的空格视为一个,这也是可能的。
我的问题
split 函数(或替代函数)是否有内置方法:
对于这个特定的例子来说,这两个都足够了(我想不出反例)
我查看了 Ali Çehreli 的《D 编程 – 教程和参考》[here],但我似乎找不到此功能。这是否意味着在 D 中你应该使用过滤器和 Lambda?
谢谢您的帮助。
split
不带任何参数即可完全满足您的要求:
When no delimiter is provided, strings are split into an array of words,
using whitespace as delimiter. Runs of whitespace are merged together
(no empty words are produced).
(这是您链接到的文档中的引用)
您可以在“分割”功能之前应用“剥离”。
output = input.strip.split;