有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java计数字符串中的符号数

假设我有这个字符串:

String helloWorld = "One,Two,Three,Four!";

如何使它计算String helloWorld中的逗号数


共 (5) 个答案

  1. # 1 楼答案

    不是那么简单,而是更短的方法

    String str = "One,Two,Three,Four!";  
    int num = str.replaceAll("[^,]","").length();
    
  2. # 2 楼答案

    如果你能导入com。拉科塔。乌提尔斯。斯特林古提尔 那就这么简单了。 导入此>;导入com。拉科塔。乌提尔斯。斯特林古提尔

    int count = StringUtils.countMatches("One,Two,Three,Four!", ",");
    System.out.println("total comma "+ count);
    
  3. # 3 楼答案

    String[] tokens = helloWorld.split(",");
    System.out.println("Number of commas: " + (tokens.length - 1));
    
  4. # 4 楼答案

    int numberOfCommas = helloWorld .replaceAll("[^,]","").length();  
    

    更多的实现可以在this site中找到

  5. # 5 楼答案

    最简单的方法是遍历字符串并对其进行计数

    int commas = 0;
    for(int i = 0; i < helloWorld.length(); i++) {
        if(helloWorld.charAt(i) == ',') commas++;
    }
    
    System.out.println(helloWorld + " has " + commas + " commas!");