Solved

how to find the repeated words

Posted on 2010-09-02
3
619 Views
Last Modified: 2012-06-27
sir,
    i m want to know  in a paragraph contains no of words like india ,pak anything. im want to know  if india repeat 4 times it will print first,if  pak repeat 3 times it will print next place to india.im want program for this concept.to align words in priority level.
0
Comment
Question by:sunda2010
3 Comments
 

Expert Comment

by:maxmetallica
ID: 33593747
You can use the org.apache.commons.lang.StringUtils class which contains many methods for string manipulation and its easier to use too.
I will write a simple program to find the word occurance...
import org.apache.commons.lang.StringUtils;
 public class word_count
{    
    public static void main(String[] args)
    {
    String string = "hello world and hello people";    
    System.out.println(StringUtils.countMatches(string,"hello")
+ " occurrences of the word 'hello' in '" + string +
                "' is found.");
    }
}
this program gives output of "2" since the word hello occurs twice.
As per ur program,use a simple sorting after this to display the occurance in descending order..Thats it!



http://www.carfab.com/apachesoftware//commons/lang/binaries/commons-lang-2.5-bin.zip
public class word_count 
{    
    public static void main(String[] args)
    {
    String string = "hello world and hello people";    
    System.out.println(StringUtils.countMatches(string,"hello")
+ " occurrences of the word 'hello' in '" + string +
                "' is found.");
    }
}

Open in new window

0
 
LVL 10

Expert Comment

by:himanshut
ID: 33593750
This will count number of characters been repeated.
If you initialize string array instead of char array then it will read the words instead + you need to you the delimiter SPACE to differentiate between two words.
import java.io.*;
import java.util.*;

class  CountCharacters {
  public static void main(String[] args) throws Exception{
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Please enter string ");
  System.out.println();
  String str=br.readLine();
  String st=str.replaceAll(" ", "");
   
  char[]third =st.toCharArray();
  for(int counter =0;counter<third.length;counter++){
  char ch= third[counter];
  int count=0;
  for ( int i=0; i<third.length; i++){
  if (ch==third[i])
  count++;
}
boolean flag=false;
for(int j=counter-1;j>=0;j--){
if(ch==third[j])
flag=true;
}
if(!flag){
System.out.println("Character :"+ch+" occurs "+count+" times ");
}
}
}
}

Open in new window

0
 
LVL 6

Accepted Solution

by:
__geof__ earned 125 total points
ID: 33594492
I have a solution that seems to work. It reads from the command line now but small changes to get input from file. It has an CustomEntry class that is comparable and a main to run the program.
###

### CustomEntry class that implements comparable to be able to sort it afterwards and a method to change a Map to a List of CustomEntry

###



public class CustomEntry implements Comparable {



    private Map.Entry entry;



    public CustomEntry(Map.Entry entry) {

        this.entry = entry;

    }



    public Map.Entry getEntry() {

        return this.entry;

    }



    public int compareTo(CustomEntry anotherEntry) {

        Integer thisIntegerVal = (Integer) (this.getEntry().getValue());

        int thisVal = thisIntegerVal.intValue();

        Integer anotherIntegerVal = (Integer) (anotherEntry.getEntry().getValue());

        int anotherVal = anotherIntegerVal.intValue();

        return (thisVal < anotherVal ? 1 : (thisVal == anotherVal ? 0 : -1));

    }



    public int compareTo(Object o) {

        return compareTo((CustomEntry) o);

    }



    public static List<CustomEntry> convertMapToList(Map map) {

        List<CustomEntry> list = new ArrayList();

        Set entrySet = map.entrySet();

        Iterator iterator = entrySet.iterator();

        while (iterator.hasNext()) {

            Map.Entry entry = (Map.Entry) iterator.next();

            CustomEntry customEntry = new CustomEntry(entry);

            list.add(customEntry);

        }

        return list;

    }

}





###

### The main method that creates the Map from the string than get it sorted and printing them

###



    public static void main(String[] args) {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Please enter string: ");

        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

        try {

            String str = br.readLine();

            String[] words = str.split(" ");

            for(String word:words){

                if(wordCount.containsKey(word)){

                    Integer i = wordCount.get(word) + 1;

                    wordCount.remove(word);

                    wordCount.put(word, i);

                }else{

                    wordCount.put(word, 1);

                }

            }

            List l = CustomEntry.convertMapToList(wordCount);

            Collections.sort(l);

            for(int i = 0; i < l.size(); i++){

                CustomEntry entry = (CustomEntry) l.get(i);

                System.out.println(entry.getEntry().getKey() + " occured " + entry.getEntry().getValue() + " times");

            }

        } catch (IOException ex) {

            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

        }



    }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
json example 39 134
Free Alternative to JIRA 4 91
JDeveloper 12c for 32 bit 4 71
servlet example issue 6 32
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now