943,083 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Marked Solved
  • Views: 7408
  • Java RSS
You are currently viewing page 1 of this multi-page discussion thread
Feb 2nd, 2010
0

Count occurence of each characters in a string

Expand Post »
Hi I want to count the number of occurence of each characters in a string from a client then the server will compute the occurences and pass back to the client the result.You may have noticed that I used String for result coz im planning to send a string to client by converting the integer found string using Integer.toString().

The client will let the user input one or more sentences then when the user inputs "im done" the server will return the number occurrence of each character in the alphabet(a-z only case ignored) from all the sentences.Then when the user types "quit" close the connection and the client program. I've tried the repaceAll() then.length but it can only be used when u want to find a single char only. Is there a method in java that lets you find a particular character? then when found increment the counter for that letter.

Java Syntax (Toggle Plain Text)
  1. import java.io.*;
  2. import java.net.*;
  3. class TCPClient
  4. {
  5. public static void main(String argv[]) throws Exception
  6. {
  7. String sentence;
  8. String result;
  9. BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
  10. Socket clientSocket = new Socket("localhost",8001);
  11. DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  12. BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  13. boolean done = false;
  14. while(done == false)
  15. {
  16. sentence = inFromUser.readLine();
  17. if (sentence.equalsIgnoreCase("im done"))
  18. {
  19. outToServer.writeBytes(sentence);
  20. result = inFromServer.readLine();
  21. System.out.println("FROM SERVER:"+ result);
  22. }
  23. else if (sentence.equalsIgnoreCase("quit"))
  24. {
  25. done = true;
  26. clientSocket.close();
  27. System.out.println("Connection closed");
  28. System.exit(0);
  29. }
  30. else
  31. outToServer.writeBytes(sentence);
  32. }
  33. }
  34. }
Java Syntax (Toggle Plain Text)
  1. import java.io.*;
  2. import java.net.*;
  3. class TCPServer
  4. {
  5. public static void main(String argv[]) throws Exception
  6. {
  7. String result;
  8. String newSentence;
  9. String sentences ="";
  10. int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;
  11. String a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1,p1,q1,r1,s1,t1,u1,v1,w1,x1,y1,z1;
  12. boolean done = false;
  13. String sentinel1 = "quit";
  14. String sentinel2 = "im done";
  15. ServerSocket welcomeSocket = new ServerSocket(8001);
  16. while(true)
  17. {
  18.  
  19. Socket connectionSocket = welcomeSocket.accept();
  20. BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
  21. DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
  22.  
  23. while(done != true)
  24. {
  25. newSentence = inFromClient.readLine();
  26. if (newSentence.equalsIgnoreCase(sentinel2))
  27. {
  28. //make a loop here to find a specific character
  29. //missing code for counting characters here converted then to type string .
  30. result ="a: "+ a1; b: "+b1+" c: "+c1+" d:"+d1+" e: "+e1+" f: "+f1+" g: "+g1+" h:"+h1+" i: "+i1+"\nj: "+ j1 +" k: "+k1+" l: "+l1+" m: "+m1+" n: "+n1+" o: "+o1+" p: "+p1+" q:"+q1+" r: "+r1+"\ns: "+ s1 +" t: "+t1+" u: "+u1+" v: "+v1+" w: "+w1+" x: "+x1+" y: "+y1+" z:"+z1;
  31. outToClient.writeBytes(result);
  32. sentences = "";
  33. }
  34. else if (newSentence.equalsIgnoreCase(sentinel1))
  35. {
  36. done = true;
  37. inFromClient.close();
  38. outToClient.close();
  39. }
  40. else
  41. sentences = sentences + newSentence;
  42. }
  43. }
  44. }
  45. }
  46.  
Similar Threads
Reputation Points: 10
Solved Threads: 2
Light Poster
jazz_vill is offline Offline
40 posts
since Nov 2009
Feb 2nd, 2010
0
Re: Count occurence of each characters in a string
Click to Expand / Collapse  Quote originally posted by jazz_vill ...
Is there a method in java that lets you find a particular character? then when found increment the counter for that letter.
Look at the Java API under the String class. There is a method called contains which will check to see if the passed in variable is present in the String.

Otherwise you could use regular expressions to search the string.

Cheers
Reputation Points: 16
Solved Threads: 31
Junior Poster
cale.macdonald is offline Offline
151 posts
since Jun 2009
Feb 4th, 2010
0
Re: Count occurence of each characters in a string
Ok here's my code:

Java Syntax (Toggle Plain Text)
  1. for (int count = 0; count < sentences.length();count ++)
  2. {
  3. //solved for a
  4. if(Character.toString(sentences.charAt(count)).equalsIgnoreCase("a")
  5. a++;
  6. else if (condition again for another letter)
  7. anyletter++;
  8. . . . up to z;
  9. }
is there another way to improve this code? so I dont have to this routine in every letter?
Last edited by jazz_vill; Feb 4th, 2010 at 7:20 am.
Reputation Points: 10
Solved Threads: 2
Light Poster
jazz_vill is offline Offline
40 posts
since Nov 2009
Feb 4th, 2010
0
Re: Count occurence of each characters in a string
Create a method that counts the occurences of a character in a give string.

Java Syntax (Toggle Plain Text)
  1. public int getCount(String toCheck, char interest)
  2. {
  3. return toCheck.replaceAll("[^"+interest"]","").length();
  4. }

Then you will want to call that from some other method

Java Syntax (Toggle Plain Text)
  1. public void printOccurences(String theString)
  2. {
  3. for(char c : theString.toCharArray())
  4. {
  5. int count = getCount(theString, c);
  6. System.out.println(c+": "+count);
  7. }
  8. }

However this will have duplicates so I would put the output into a Map and print it only if its not already present.

Cheers
Reputation Points: 16
Solved Threads: 31
Junior Poster
cale.macdonald is offline Offline
151 posts
since Jun 2009
Feb 5th, 2010
0
Re: Count occurence of each characters in a string
Click to Expand / Collapse  Quote originally posted by jazz_vill ...
Ok here's my code:


is there another way to improve this code? so I dont have to this routine in every letter?

The ASCII values for A-Z are 65 to 90. You could loop over those integers to search for your characters.

Easier still, you could create a string of the alphabet "abcdef..." and turn it into a character array and loop over that.

But, yes, avoid hardcoding every letter in.
Sponsor
Reputation Points: 318
Solved Threads: 135
LINQ!
apegram is offline Offline
550 posts
since Jan 2010
Feb 7th, 2010
0
Re: Count occurence of each characters in a string
@apegram i dont really get it...

do you mean first i'll create an array which contains the alphabet;
then convert the sentences (all of the input sentence of the user) into another array.

loop over the array of characters and on the array of sentences and compare its value?

do i need another array to store the result?
Reputation Points: 10
Solved Threads: 2
Light Poster
jazz_vill is offline Offline
40 posts
since Nov 2009
Feb 7th, 2010
0
Re: Count occurence of each characters in a string
What you could is traverse the entire string, character by character. At each character, check the char and increase it's count. You would have to maintain 26 different counters - one for each letter of the alphabet.
Use the switch-case construct to check the chars. Something like below:

Java Syntax (Toggle Plain Text)
  1. switch(char){
  2. case 'a' or 'A': {aCtr++; // increase a's counter
  3. break;}
  4. case 'b' or 'B': {bCtr++; // increase b's counter
  5. break;}
  6. // rest of the code...
  7. }
Reputation Points: 485
Solved Threads: 89
Posting Shark
verruckt24 is offline Offline
944 posts
since Nov 2008
Feb 7th, 2010
0
Re: Count occurence of each characters in a string
@verruckt24 thats what we want to avoid to hardcode on every letter if you look on the previous post I've done a code that works almost the same(see post#3)... thanks for the idea BTW
Reputation Points: 10
Solved Threads: 2
Light Poster
jazz_vill is offline Offline
40 posts
since Nov 2009
Feb 7th, 2010
0
Re: Count occurence of each characters in a string
Write String data to your DataOutputStream using the writeUTF method and read the same at the server using the readUTF method of the DataInputStream. Another option would be to write to the OutputStream by wrapping it in a PrintWriter and then at the client using the BufferedReader to read the same. Then:
  • Initialize a Map of String to Integer
  • Loop over the characters present in the String
  • For each character, check if it's a letter using the utility methods of the Character class
  • Check the presence of the character in the Map, if isn't not present, place the character in the Map with the value as 1 otherwise increment the value for the given character in the Map (you can apply the same logic using arrays if you need performance but I don't think you should concern yourself with these things right now)
Also, are you planning to use this code for a single client given that your TCPServer is stateful (since it remembers the previous string passed in)?
Last edited by ~s.o.s~; Feb 7th, 2010 at 9:54 am.
Super Moderator
Featured Poster
Reputation Points: 3233
Solved Threads: 719
Failure as a human
~s.o.s~ is offline Offline
8,871 posts
since Jun 2006
Aug 21st, 2011
0

Occurence of each characters in a String - Java

Java Syntax (Toggle Plain Text)
  1. public class Count{
  2.  
  3. String str = "Hello World", s = str;
  4. int count = 0;
  5.  
  6. public int show(){
  7. while(s.length()>0){
  8. count = 0;
  9. for(int i=0;i<s.length();i++){
  10. if(s.charAt(i)==s.charAt(0))
  11. count++;
  12. }
  13. System.out.println(s.charAt(0)+": "+count);
  14. s = s.replace(String.valueOf(s.charAt(0)), "");
  15. }
  16. }
  17. public static void main(String[] ar){
  18. new Count().show();
  19. }
  20. }

--------------------------------------------------------------------------------
OUTPUT:
H: 1<br />
e: 1<br />
l: 3<br />
o: 2<br />
WSpace: 2<br />
W: 1<br />
r: 1<br />
d: 1
Reputation Points: 10
Solved Threads: 1
Newbie Poster
Alochious is offline Offline
1 posts
since Aug 2011

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: usage of get and set method with arrays
Next Thread in Java Forum Timeline: Help needed urgently!





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC