Click here to Skip to main content
15,071,928 members
Please Sign up or sign in to vote.
1.80/5 (5 votes)
See more:
String str="1-300,1-300,1-300,1-200,1-200";

MY output is

i have to count 1-300 is 3 times 1-200 is 2 time
Updated 2-Oct-12 22:49pm
Kenneth Haugland 3-Oct-12 3:50am
Ok, thanks for shearing..

Ok, this is a homework task.
I will give you advice, but no code - at least no complete.

So what to do?

First of all you need to split the String. This can be done by using StringTokenizer[^]:

String strValue="1-300,1-300,1-300,1-200,1-200";
StringTokenizer oTokenizer = new StringTokenizer(strValue, ",");

You can then loop through the StringTokenizer by using, which returns the next value. Remember: loop. That's a for or while loop.

Other version:
The String can be split by the String's own method String.split(String strDelimiter)[^]. That one returns a String Array, which you can also loop through.

After the splitting is done you'll just have to compare each bit with the others. That's a loop in a loop. I'll let you figure that out, I guess that's the idea of this homework.

I strongly suggest to read the documentation for the String Object (see link above), cause that's one you will have to deal with very often.

Have fun and please ask when you have additional questions or need further explanation.
ridoy 3-Oct-12 5:31am
Take a look at the indexOf() method of the String[^] class.
Perfect Work with Perfect Answer

public class CountYourRepeatedValue{
public static int countNo(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();

public static void main(String[] args){
System.out.println(countNo("1-300", "1-300,1-300,1-300,1-200,1-200"));



Haresh Prajapati
TorstenH. 3-Oct-12 8:29am
Is that what your teacher told you?
hareshdgr8 4-Oct-12 5:45am
no i did my self actually this is last option in my mind ......
TorstenH. 4-Oct-12 5:53am
It's just half the answer.
You should think about it again. Also try other String Arrays.
Additional question: Is it given that you know the String you need to count? What if you do not know the String you are counting?
hareshdgr8 4-Oct-12 6:03am
hey you just looping your single content like use for loop or while loop and match with main string i.e. 1-300,1-300,1-300,1-200,1-200

TorstenH. 4-Oct-12 6:57am
yeah - "just".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900