Solved

strCount chalenge

Posted on 2016-09-23
3
99 Views
Last Modified: 2016-09-23
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
Comment
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
  • Learn & ask questions
  • 2
3 Comments
 
LVL 7

Author Comment

by:gudii9
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);
	    	  
	    	}
}

Open in new window

above passed all tests. an improvements or alternate approaches?
0
 
LVL 27

Accepted Solution

by:
rrz earned 500 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);
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 41812892
i like above approach
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

A short article about a problem I had getting the GPS LocationListener working.
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question