以下是使用dlang语言原生实现的str_word_count函数,实现统计单词数目:

int str_word_count(string str) {
    int count = 0;
    bool is_word = false;
    foreach (char c; str) {
        if (isAlphaNum(c)) {
            is_word = true;
        } else if (is_word) {
            count++;
            is_word = false;
        }
    }
    if (is_word) {
        count++;
    }
    return count;
}

bool isAlphaNum(char c) {
    return isAlpha(c) || isNum(c);
}

bool isAlpha(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

bool isNum(char c) {
    return c >= '0' && c <= '9';
}

该函数会遍历字符串中的每一个字符,如果当前字符是字母或数字,则认为其属于一个单词,当遇到非字母或数字的字符时,则表示这个单词结束,计数器加1,并将is_word标记为false。当遍历完成后,如果is_word为true,则说明最后一个单词没有被计数,需要将计数器加1

dlang语言原生实现php的str_word_count统计单词数目注意特殊字符标点字符空格也应该都作为单词分界线另外尽量不要用标准库感谢您的回答

原文地址: https://www.cveoy.top/t/topic/fmX8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录