Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# strCount chalenge

Posted on 2016-09-23
Medium Priority
117 Views
Hi,

I am working on below challenge.
http://codingbat.com/prob/p186177
Psedo code:
1. check  if str has sub string if yes increment by 1 or repeat

I wrote my code as below and not passing all tests
``````public int strCount(String str, String sub) {
if (str.length() <2){
return 0;
}
if (str.startsWith( sub) {
return 1 + strCount(str.substring(2));
}
else {
return strCount(str.substring(1));

}
}
``````

Compile problems:

Error:      if (str.startsWith( sub) {
^
Syntax error on token ")", ) expected after this token

see Example Code to help with compile problems

Any improvements or alternate approaches?

0
Question by:gudii9
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 7

Author Comment

ID: 41812763
``````public int strCount(String str, String sub) {
if (str.length() <sub.length()){
return 0;
}
if ((str.substring(0,sub.length()).equals(sub))) {
return 1 + strCount(str.substring(sub.length()),sub);
}
else {
return strCount(str.substring(1),sub);

}
}
``````
above passed all tests. an improvements or alternate approaches?
0

LVL 28

Accepted Solution

rrz earned 2000 total points
ID: 41812849
Here is my code.
``````public int strCount(String str, String sub) {
int index = str.indexOf(sub);
if(index == -1 || str.length() < sub.length())return 0;
return 1 + strCount(str.substring(index + sub.length()), sub);
}
``````
0

LVL 7

Author Comment

ID: 41812892
i like above approach
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Make the most of your online learning experience.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Progress
###### Suggested Courses
Course of the Month11 days, 4 hours left to enroll