Java不同单词个数统计

描述

编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如:对于句子“one little two little three little boys”,总共有5个不同的单词:one, little, two, three, boys。
说明:(1)输入的句子当中只包含英文字符和空格,单词之间用一个空格隔开;(2)不用考虑单词的大小写,假设输入的都是小写字符;(3)句子长度不超过100个字符。

输入

输入只有一行,即一个英文句子。

输出

输出只有一行,是一个整数,表示句子中不同单词的个数。

难度

入门

输入示例

one little two little three little boys

输出示例

5

完成代码:

 1 import java.util.Scanner;
 2 
 3 public class Demo01{
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         int n=0;                                             //n统计有多少个不同单词,a保存单词,b判断是否有重复单词,设当b=1表示为重复单词
 7         String str=sc.nextLine();
 8         String[] a=str.split(" ");
 9         int[] b=new int[a.length];
10         for(int i=0;i<a.length;i++){                //从第一个开始遍历
11             String t1=a[i];                         //用t1保存第i个单词
12             for(int j=i+1;j<a.length;j++){
13                 String t2=a[j];                     //用t2保存第j个单词
14                 if(b[i]!=1){                        //b[i]==1表示被访问的单词为重复单词,会跳出循环
15                     if(t1.length()==t2.length()){   //如果两个单词长度不同证明是不同单词,继续访问下一个单词
16                         int flag=0;                 //标记两个单词是否一样,若一样的话将在b进行标记
17                         for(int h=0;h<t1.length();h++)
18                             if(t1.charAt(h)!=t2.charAt(h)) {
19                                 flag = 1;
20                                 break;
21                             }
22                         if(flag==0)
23                             b[j]=1;
24                     }
25                 }
26             }
27         }
28         for(int i=0;i<a.length;i++){
29             if(b[i]==0)
30                 n++;
31         }
32         System.out.println(n);
33         sc.close();
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/Blogwjl/p/12326980.html