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
What is finalize()?
Is array size fixed in java?
Does A Class Inherit The Constructors Of Its Superclass?
What java ide should I use?
Explain the difference between transient and volatile in java?
What is Mutex (Mutual Exclusion Object) ?
Which programming language is most secure?
Explain about the security aspect of java?
design an lru cache in java?
What is object-oriented paradigm?
What is a treeset class?
What about member inner classes?
explain multi-threading in java?
What is the hashcode () and equals () used for?
Give a practical example of singleton class usage?