[关闭]
@XQF 2018-03-07T22:59:35.000000Z 字数 532 阅读 935

如何统计一行字符里的单词数?

数据结构与算法


大一的老朋友了。。。。主要是判断空白字符(换行,空格和标点)

split也是正则

1.低级情况的处理

低级情况就是这一行字符中只有非空白字符和空格,。,。split(" ");

2.高级情况

  1. public class Solution {
  2. public int countWords(String string) {
  3. if(string==null||string.length()==0){
  4. return 0;
  5. }
  6. String patternString = "\\w+";
  7. Pattern p = Pattern.compile(patternString);
  8. Matcher m = p.matcher(string);
  9. int counter = 0;
  10. while (m.find()) {
  11. counter++;
  12. }
  13. return counter;
  14. }
  15. public static void main(String[] args) {
  16. Solution solution = new Solution();
  17. String string = "abac 33,3333";
  18. System.out.println(solution.countWords(string));
  19. }
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注