欢迎访问宙启技术站
智能推送

Java函数:如何使用Java函数获取字符串中指定子字符串出现的次数?

发布时间:2023-05-20 17:35:56

在Java中,可以使用内置的函数和算法来获取字符串中指定子字符串出现的次数。下面将介绍两种常见的方法。

方法一:使用indexOf()和substring()函数。

indexOf()函数可以用来查找子字符串在父字符串中 次出现的位置,如果查找失败则返回-1。substring()函数可以用来截取字符串的子串。使用这两个函数可以找到指定子字符串出现的次数。

代码实现:

public static int countSubstring(String str, String sub) {
    int count = 0;
    int idx = str.indexOf(sub);
    while (idx != -1) {
        count++;
        str = str.substring(idx + sub.length());
        idx = str.indexOf(sub);
    }
    return count;
}

使用该函数可以获取子字符串在父字符串中出现的次数。例如,对于字符串"hello world, hello java, hello python",使用函数int count = countSubstring("hello world, hello java, hello python", "hello");,输出的count为3,即“hello”出现了3次。

方法二:使用正则表达式。

正则表达式是一种文本模式匹配的方法,可以用来快速查找和替换字符串。通过正则表达式可以轻松地查找指定子字符串出现的次数。

代码实现:

public static int countSubstringRegex(String str, String sub) {
    Pattern pattern = Pattern.compile(sub);
    Matcher matcher = pattern.matcher(str);
    int count = 0;
    while (matcher.find()) {
        count++;
    }
    return count;
}

使用该函数可以获取子字符串在父字符串中出现的次数。例如,对于字符串"hello world, hello java, hello python",使用函数int count = countSubstringRegex("hello world, hello java, hello python", "hello");,输出的count为3,即“hello”出现了3次。

总结:无论是使用indexOf()和substring()函数,还是使用正则表达式,都能够方便地获取字符串中指定子字符串出现的次数。选择方法需要根据实际需求和使用场景进行权衡。