java如何判断字符串中有几个标点符号和空格

java该如何判断字符串中有几个空格和标点符号?无知的我请求各位给个方法

public static void countPunctuationAndSpaces(String str) {
    // 匹配标点符号和空格的正则表达式
    String regex = "[\\pP\\pZ]";
    
    int punctuationCount = 0;
    int spaceCount = 0;
    
    // 使用正则表达式匹配字符串中的标点符号和空格
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);
    
    while (matcher.find()) {
        String matchedStr = matcher.group();
        if (matchedStr.matches("\\pP")) {
            punctuationCount++;
        } else if (matchedStr.matches("\\pZ")) {
            spaceCount++;
        }
    }
    
    System.out.println("标点符号的数量为:" + punctuationCount);
    System.out.println("空格的数量为:" + spaceCount);
}
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/208626
  • 你也可以参考下这篇文章:Java开源数据库引擎,数据库计算封闭性的一站式解决方案
  • 除此之外, 这篇博客: Java在长字符串中查找短字符串的多种方法中的 Java在长字符串中查找短字符串的多种方法 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 方案一:
    补充:在输入短字符串时,如果有空格,可以在比较前用 trim()方法截取前后空白

     /*该方法只适用于有特殊分割符号的字符串*/
            System.out.println("请输入字符串:");
            Scanner str1=new Scanner(System.in);
            String s=str1.nextLine();
            System.out.println("请输入第二个字符串:");
            Scanner str2=new Scanner(System.in);
            String  s2=str2.next();
            String[] i= s.split(" ");//对长字符串进行分割得到一个字符串数组
            int o=0;
            for (int j = 0; j <i.length ; j++) {
                if (s2.equals(i[j])==true){//对字符数组进行遍历比较
                    o++;
                }
            }
            System.out.println("次数为:"+o);
        }
    
    

    方案二:

     //如果替换未造成字符串长度损失,该方法则不适用
            System.out.println("请输入一个长字符串:");
            Scanner str1 = new Scanner(System.in);
            String s = str1.nextLine();
            System.out.println("请输入短字符串:");
            String s1 = str1.nextLine();
            String s3 = s.replaceAll(s1, "0");//字符替换
            int b1 = s.length() - s3.length();//计算出s字符串损失的长度
            int b2 = b1 / (s1.length() - 1);//根据规律计算出s1字符串在s字符串中出现的次数
            System.out.println("次数为:"+b2);
    

    方案三:

        //该方法适用于各种模式
            System.out.println("请输入一个长字符串:");
            Scanner str1 = new Scanner(System.in);
            String s = str1.nextLine();
            System.out.println("请输入短字符串:");
            String s1 = str1.nextLine();
            int c=0;
            for (int i = 0; i <s.length()-s1.length() ; i++) {
                if (s1.equals(s.substring(i,i+s1.length()))){/*字符串比较,对长字符串进行截取,之后用截取得到的字符串与短字符串进行比较*/
                    ++c;
                }
            }
            System.out.println("次数为: " + c);
    
    

    关注我,为您奉上更多有趣的方法。