我想要一个java程序输入一个字符串,并显示出现的每个唯一的单词没有任何内置的方法



我编写的这个程序用于显示给定字符串中可用的单词数。现在我想要occurenceof字符串中每个单词的逻辑,而不使用任何内置方法。

import java.util.Scanner;
 public class Test80 
 {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        System.out.println("Enter your sentence:[Try to ignore space at end]");
        String s=in.nextLine();
        System.out.println("Size of the string is "+s.length());
        int res=count(s);
        System.out.println("No of words in the given String --->>"+"  "+s+" :"+"is"+" :"+res);
    }

    private static int count(String s) {
        int count=0;
        if(s.charAt(0)!=' ')
        {
            count++;
        }
        for(int i=0;i<s.length();i++)
         {
            if((s.charAt(i)==' ')){
                count++;
           }
        }
        return count;
    }
}

如果一个句子中有'n'个空格,那么单词的数量将是n+1,而不是做所有这些;

用if else修改程序。

在count方法中执行以下操作

private static int count(String s) {

    int count=0;
    for(i=0;i<s.length();i++)
    {
      if(s.charAt(i)==' ') count++;
    }
    return (count+1);//returning the number of words
}

根据您对内置方法的定义,您应该为该任务使用Map。

Map<String,Integer> = new HashMap<>();
int begin_pos = 0;
for(int i = 0; i < s.length(); i++){
    if(s.charAt(i) == ' '){
        int count = map.containsKey(s.substring(begin_pos, i)) ? map.get(s.substring(begin_pos, i)) : 0;
        map.put(s.substring(begin_pos, i), count + 1);
        begin_pos = i+1;
    }
    else if(i == s.length() -1){
        int count = map.containsKey(s.substring(begin_pos)) ? map.get(s.substring(begin_pos)) : 0;
        map.put(s.substring(begin_pos), count + 1);
    }
}

相关内容

最新更新