簡體   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