Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 127
  • Last Modified:

strCount chalenge

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));
	    	  
	    	}
}

Open in new window


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?      

please advise
0
gudii9
Asked:
gudii9
  • 2
1 Solution
 
gudii9Author Commented:
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);
	    	  
	    	}
}

Open in new window

above passed all tests. an improvements or alternate approaches?
0
 
rrzCommented:
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);
}

Open in new window

0
 
gudii9Author Commented:
i like above approach
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now