以下是 D 语言的原生实现:

import std.stdio;

int substr_count(string haystack, string needle, int offset = 0, int length = -1) {
    if (length == -1) {
        length = haystack.length - offset;
    }
    if (offset < 0 || offset >= haystack.length || length < 0 || offset + length > haystack.length) {
        return 0;
    }
    int count = 0;
    while (true) {
        int idx = haystack.indexOf(needle, offset);
        if (idx == -1 || idx >= offset + length) {
            break;
        }
        count++;
        offset = idx + needle.length;
    }
    return count;
}

void main() {
    string haystack = 'hello world!';
    string needle = 'l';
    int count = substr_count(haystack, needle);
    writeln(count); // 3
}

上述代码中,我们首先检查偏移量和长度是否合法,如果不合法则直接返回 0。然后使用 D 标准库的 indexOf 函数查找子字符串出现的位置,如果找不到则退出循环,否则增加计数器并更新偏移量,直到偏移量超过指定的长度。最后返回计数器的值。

在 main 函数中,我们定义了一个字符串 haystack 和子字符串 needle,并调用 substr_count 函数计算 needle 在 haystack 中出现的次数,并打印出来。

Dlang 原生实现 substr_count 函数 - 统计字符串中子字符串出现次数

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

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