查询字符串中指定字符个数 java
  XRbPOD5alAUE 2023年11月02日 72 0

查询字符串中指定字符个数的方法

引言

在Java开发中,我们经常会遇到需要查询字符串中指定字符个数的需求。这个需求可以通过一些简单的方法实现,本文将介绍几种常用的方法,并提供相应的示例代码。

方法一:使用循环遍历字符串

这种方法是最直观的思路,我们可以使用一个循环来遍历字符串的每个字符,然后判断是否与指定字符相等。如果相等,则计数器加一。

public class StringUtils {
    public static int countChar(String str, char c) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == c) {
                count++;
            }
        }
        return count;
    }
}

这个方法的时间复杂度是O(n),其中n是字符串的长度。

方法二:使用Java 8的Stream API

Java 8引入了Stream API,可以简化对集合的操作。我们可以使用Stream的filter操作来筛选出指定字符,并使用count操作来计数。

import java.util.stream.Stream;

public class StringUtils {
    public static int countChar(String str, char c) {
        return (int) str.chars()
                .filter(ch -> ch == c)
                .count();
    }
}

这个方法的时间复杂度也是O(n)。

方法三:使用正则表达式

正则表达式是一种强大的模式匹配工具,我们可以使用正则表达式来匹配指定字符,并使用Matcher的find方法来计数。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    public static int countChar(String str, char c) {
        Pattern pattern = Pattern.compile(String.valueOf(c));
        Matcher matcher = pattern.matcher(str);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }
}

这个方法的时间复杂度和正则表达式的复杂度有关。

方法四:使用Apache Commons Lang库

Apache Commons Lang是一个常用的Java工具库,其中提供了StringUtils类,包含了很多字符串操作的方法。我们可以使用StringUtils的countMatches方法来计数指定字符出现的次数。

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDemo {
    public static void main(String[] args) {
        String str = "Hello, world!";
        char c = 'o';
        int count = StringUtils.countMatches(str, c);
        System.out.println("Count: " + count);
    }
}

为了使用Apache Commons Lang库,你需要在项目中添加相应的依赖。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

总结

本文介绍了四种常用的方法来查询字符串中指定字符的个数。这些方法各有优劣,可以根据实际情况选择合适的方法。希望本文对你有所帮助!

类图

classDiagram
    StringUtils <-- StringUtilsDemo

类图表示了本文介绍的示例代码中的类之间的关系。

参考资料

  • [Java String中查询指定字符出现的次数](
  • [Java 8 Stream API Tutorial](

源代码链接

[GitHub](

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: 北向接口 java 下一篇: 本地文件 JAVA Linux
  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   55   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   111   0   0 Java
  8s1LUHPryisj   2024年05月17日   47   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
XRbPOD5alAUE