0

In this example i m not able to count "manoj" in the given string...how i can do this..

String text = "manoj kumjjjartiwarimanojmanoj";
char[] line = text.toCharArray();
char[] temp = "manoj".toCharArray();
int count=0;

for (int i =0; i < line.length; i++) {  
    int t =0;
    for (int j = 0; j < temp.length; j++) {
        if(line[i]==temp[j]){
            t=1;
        }
        else{
            t=0;
        }
    }
    if(t==1){
        count=count+1;
    }
}
System.out.println(count);
2

3 Answers 3

3

You can use a combination of substring and startsWith of the String class directly:

String text = "manoj kumjjjartiwarimanojmanoj";
String search = "manoj";

int count = 0;
for (int i=0; i < text.length() - search.length(); i++) {
    if (text.substring(i).startsWith(search)) {
        count++;
    }
}
System.out.println(count);

Prints 2

This will also count all occurrences in cases like searching for "aa" in "aaaaaa" (resulting in 5).

Sign up to request clarification or add additional context in comments.

Comments

1

It can be done with various method , you should really search this on google before asking, but i am providing a code

String text = "manoj kumjjjartiwarimanojmanoj";

Pattern p = Pattern.compile("manoj");
Matcher m = p.matcher(text);
int count = 0;
while (m.find())
{
   count +=1;
}

1 Comment

A simple for loop starting at each character would be much cheaper.
0
String pattern="manoj"
String text = "manoj kumjjjartiwarimanojmanoj";
String text2 = text.replaceAll (pattern, "") 
(text.length() - text2.length())/pattern.length ()

Result: 3, is it correct?

Note, that a resulting manoj, like in input "mamanojnoj" will not be replaced by replaceAll, which might be in your interest.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.