繁体   English   中英

Java计数字符串中的单词

[英]java count words in string

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

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));

    }

}

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

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

只需更改String space=""; String space=" "; String space="\\\\s+"; ,您一切顺利!

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

String space="";

是错的。 这是一个空字符串,将被错误地使用。

你最好用

     String space="\\s+"; 

要么

    String space=" ";

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

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

 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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM