Dlang 实现字符串单词计数:类似 PHP Str::wordCount 功能
Dlang 实现字符串单词计数:类似 PHP Str::wordCount 功能
使用 Dlang 语言实现类似 PHP Str::wordCount 功能的代码,能够统计字符串中的单词数目,并去除空格和标点符号。
PHP 代码示例:
use Illuminate\Support\Str;
Str::wordCount('Hello, world!'); // 2
Dlang 代码实现:
import std.algorithm;
import std.array;
import std.ascii;
import std.string;
int wordCount(string str) {
auto words = str
.filter!(c => !isPunct(c) && !isSpace(c))
.split(isSpace);
return words.length;
}
void main() {
string str = 'Hello, world!';
int count = wordCount(str);
writeln(count); // 2
}
代码说明:
wordCount函数接受一个字符串参数str,并返回该字符串中的单词数。- 使用
filter!方法过滤掉字符串中的所有标点符号和空格。 - 使用
split方法将过滤后的字符串按照空格分割成单词数组。 - 返回单词数组的长度,即单词数。
示例:
在 main 函数中,我们传入一个字符串 'Hello, world!' 到 wordCount 函数,最终输出的单词数为 2。
总结:
该 Dlang 代码通过简单的过滤和分割操作,实现了类似 PHP Str::wordCount 的功能,能够统计字符串中的单词数目,并去除空格和标点符号。
原文地址: https://www.cveoy.top/t/topic/odaC 著作权归作者所有。请勿转载和采集!