Hi,

This is ravi i have a question like this i have string
"UNDERSTAND" now i want to count the letters how many times
it occures.i.e from the above string the out put should be
like this U-1,N-2,D-2,E-1,R-1,S-1,T-1,A-1.
how can i achieve this

Thnaks in advance for your response ..

Answer Posted / kanthi

well, one way of doing this is to take up a counter
variable initialised to 0. Then, there will be 2 for loops.
First one starts at 0 and the second one starts at 1+(the
upper loop variable) and both iterate for a
UNDERSTAND.length() . In the loop, u can start by comparing
each char in the string with every other char using charAt
() method. If a match is found then increment the counter
variable. At the end of the inner loop, u will have the
number of times a particular character is repeated. Just
print the result out. That way, counter variable can be
reused for the next character again.

Code might be something like this:
int counter = 0;
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++)
{
if(charAt(i).equals(charAt(j))
counter++;
}
System.out.println(charAt(i) + '-' + counter);
}

Hope this works.. please tell me if u find any mistake with
the logic.

Is This Answer Correct ?    1 Yes 6 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is an empty list in java?

531


How can we pass argument to a function by reference instead of pass by value?

588


Can we start a thread twice in java?

511


What is the difference between array list and vector in java?

509


What is the difference between double and float variables in java?

637






What are keywords and reserved words in java?

560


What is meant by anonymous class?

595


What super () does in java?

486


What is static import?

602


What are the advantages of packages in java?

573


What is difference between path and classpath in java?

487


What does java se mean?

591


How do you define a variable?

539


Define how does a try statement determine which catch clause should be used to handle an exception?

587


What is hashmap and map?

560