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);
}
方案一:
补充:在输入短字符串时,如果有空格,可以在比较前用 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);
关注我,为您奉上更多有趣的方法。