【问题标题】:java count words in stringjava统计字符串中的单词
【发布时间】:2017-12-17 13:46:05
【问题描述】:

我正在编写代码来查找字符串中的单词数,代码如下:

package exercises;

import java.util.Scanner;

public class count {

    public static int countwords(String str){
        int count=0;
        String space="";
        String[] words=str.split(space);
        for(String word:words){
            if(word.trim().length()>0){
                count++;
            }

        }
        return count;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter the string");
        Scanner input=new Scanner(System.in);
    String s=input.nextLine();
    System.out.println(countwords(s));

    }

}

为了练习,我再次将这段代码写成

package exercises;

import java.util.Scanner;

public class count {

    public static int countwords(String str){
        int count=0;
        String space="";
        String[] words=str.split(space);
        for(String word:words){
            if(word.trim().length()>0){
                count++;
            }

        }
        return count;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter the string");
        Scanner input=new Scanner(System.in);
    String s=input.nextLine();
    System.out.println(countwords(s));

    }

}

我只是想知道为什么这些代码的代码输出不同?虽然我逐行检查了代码,但我找不到这两个代码的输出不同的原因?谁能帮忙

【问题讨论】:

  • 你在str.split("") 失去了我...你为什么要分割空字符串,而不是空格(或空白)?

标签: java string count words


【解决方案1】:

由于您的拆分字符串是"",因此每个字母都将被提取为一个单词。

只需将String space=""; 更改为String space=" ";String space="\\s+";,您就可以开始了!

正则表达式工具\\s+ 表示应该在出现一次或多次空格后拆分字符串。

【讨论】:

  • 谢谢你的作品。还有任何建议可以让这段代码更好吗?还必须添加什么才能在字符串中查找唯一和重复的单词。
  • @ppkumar 随时:)
【解决方案2】:
String space="";

错了。是空字符串,会用错。

你最好用

     String space="\\s+"; 

    String space=" ";

正则表达式“\\s+”是“一个或多个空格符号”

【讨论】:

  • 你的意思不是“\\s+”吗?
【解决方案3】:

另一种选择可能是这样的:

 public static void main(String[] args) {
    System.out.println("Enter the string");
    Scanner input=new Scanner(System.in);
    String line=input.nextLine();
    System.out.println(Arrays.stream(line.split(" ")).count());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2023-03-21
    • 2021-05-10
    相关资源
    最近更新 更多