Monday, August 20, 2012

how to count selected word in string using java


Output:

java contents  3 times.

package com.swain.cell;

import java.util.HashMap;
import java.util.StringTokenizer;

public class DuplicateString {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub

        String str = "java java android android java example";
        String selectedword="java";
        
        StringTokenizer t = new StringTokenizer(str);
        HashMap<String,Integer> hms=new HashMap<String,Integer>();
       
              while(t.hasMoreTokens())
              {
                    
                     String word = t.nextToken();
                      hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));
             
              }
              System.out.println(selectedword+" contents  " + hms.get(selectedword)+ " times.");
       
   
       }

}


Check here video.




No comments:

Post a Comment

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...