java-判断字符串中英文单词个数

版权声明:转发者请注明地址哦-----kuls的博客-一个正在疯狂学习的大学生- https://blog.csdn.net/qq_36547531/article/details/82215231

这里写图片描述

题目如图! 第一次写,还看错题目了, ̄□ ̄|| 今早又来想下,忽然间发现了一个String中的方法split(),于是我打开API 如下:

 String[] split(String regex) 
          根据给定正则表达式的匹配拆分此字符串。 
 String[] split(String regex, int limit) 
          根据匹配给定的正则表达式来拆分此字符串。 

是可以把一段字符根据指定元素拆分的,regex里面用正则表达式。 于是查完空格得到正则表达式

\p{Space} 空白字符:[ \t\n\x0B\f\r] 
\s 空白字符:[ \t\n\x0B\f\r] 

都可以用。 然后我就开始写代码了,

public class Blank {
public static void main(String[] args) {
   int blank=0;
    String txt="Hello   World I";
    String[] count1 =txt.split("[ \\t\\n\\x0B\\f\\r]");
    int len=count1.length;
    for (int i = 0; i < count1.length; i++) {
        if (count1[i].equals("")) {
        blank++;
        }
    }

    System.out.println("单词个数:"+(len-blank));    
     }
}

这里有个小小的计算,就是整个分出来的数组的长度减去空格的数量就是单词的个数了!

若有错误请指出,谢谢!

猜你喜欢

转载自blog.csdn.net/qq_36547531/article/details/82215231
今日推荐