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.

import java.io.*; 
import java.net.*; 
class TCPClient
{ 
    public static void main(String argv[]) throws Exception 
    { 
        String sentence; 
        String result;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
        Socket clientSocket = new Socket("localhost",8001); 
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		boolean done = false;
		while(done == false)
		{
			sentence = inFromUser.readLine(); 
			if (sentence.equalsIgnoreCase("im done"))
				{
				outToServer.writeBytes(sentence);
				result = inFromServer.readLine(); 
				System.out.println("FROM SERVER:"+ result);
				}
			else if (sentence.equalsIgnoreCase("quit"))
			{
				done = true;
				clientSocket.close();
				System.out.println("Connection closed");
				System.exit(0);
			}
			else
				outToServer.writeBytes(sentence);
		} 
    } 
}
import java.io.*; 
import java.net.*; 
class TCPServer
{ 
	public static void main(String argv[]) throws Exception 
    { 
      String result;
	  String newSentence;
	  String sentences ="";
	  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;
	  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;
      boolean done = false;
	  String sentinel1 = "quit";
	  String sentinel2 = "im done";
      ServerSocket welcomeSocket = new ServerSocket(8001); 
	  while(true)
	  {
    	   
           Socket connectionSocket = welcomeSocket.accept(); 
           BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 
           DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
			
		  while(done != true)
		  {
				newSentence = inFromClient.readLine();
				if (newSentence.equalsIgnoreCase(sentinel2))
				{
                                   //make a loop here to find a specific character
                                  //missing code for counting  characters here converted then to type string .
				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;
					outToClient.writeBytes(result);
					sentences = "";
				}
				else if (newSentence.equalsIgnoreCase(sentinel1))
				{
					done = true;
					inFromClient.close();
					outToClient.close();
				}
				else
					sentences = sentences + newSentence; 
			}
		}
    } 
}

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

Ok here's my code:

for (int count = 0; count < sentences.length();count ++)
{
   //solved for a
   if(Character.toString(sentences.charAt(count)).equalsIgnoreCase("a")
   a++;
   else if (condition again for another letter)
   anyletter++;
   . . . up to z;
}

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

Edited 6 Years Ago by jazz_vill: n/a

Create a method that counts the occurences of a character in a give string.

public int getCount(String toCheck, char interest) 
{
	return toCheck.replaceAll("[^"+interest"]","").length();	
}

Then you will want to call that from some other method

public void printOccurences(String theString)
{
          for(char c : theString.toCharArray())
          {
                  int count = getCount(theString, c);
                  System.out.println(c+": "+count);
          }
}

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

Cheers

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.

@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?

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:

switch(char){
    case 'a' or 'A': {aCtr++; // increase a's counter
          break;} 
    case 'b' or 'B': {bCtr++; // increase b's counter
          break;} 
    // rest of the code...
}

@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

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)?

Edited 6 Years Ago by ~s.o.s~: n/a

public class Count{

    String str = "Hello World", s = str;
    int count = 0;
    
    public int show(){
        while(s.length()>0){
            count = 0;
            for(int i=0;i<s.length();i++){
                if(s.charAt(i)==s.charAt(0))
                    count++;
            }
            System.out.println(s.charAt(0)+": "+count);
            s = s.replace(String.valueOf(s.charAt(0)), "");
        }
     }
     public static void main(String[] ar){
         new Count().show();
     }
}

--------------------------------------------------------------------------------
OUTPUT:
H: 1
e: 1
l: 3
o: 2
WSpace: 2
W: 1
r: 1
d: 1

Seems like a lot of work for nothing. Why go through all the loops etc?
How does this code relate to the problem that was posted over ONE YEAR AGO?

package com.test;

import java.util.HashMap;

public class AlphaCount 
{

    public static void main(String[] args) {
        HashMap<Character,Integer> hm=new HashMap <Character,Integer>();
        char c='/';
        char d;
        int counter=0;
        String s="mmmma  aahhhaa";
        int l=s.length();

        for(int i=0;i<l;i++)
        {
            c=s.charAt(i);

            {
                if(hm.containsKey(s.charAt(i))==false)
                for (int j=i;j<l;j++)
                {
                    d=s.charAt(j);
                    if(c==d )
                    {
                        counter++;
                    }

                    hm.put(c,counter);
                }

            }
            counter=0;
        }



        System.out.println(hm);
    }
}
This question has already been answered. Start a new discussion instead.