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

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

substring count challenge

Hi,

I am working on below challenge
http://codingbat.com/prob/p198640

i wrote code as below
public class Test27 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int numberCount=stringMatch("abc","abc");
		System.out.println("is-->"+numberCount);
	}
	
	
	public static int stringMatch(String a, String b) {
		int count=0;
		for(int i=0;i<=a.length()-1;i++){
		if(a.substring(i,i+1)==a.substring(i,i+1))
		count++;
		}
		return count;
		  
		}

}

Open in new window


I have many test cases failing as below

Expected      Run            
stringMatch("xxcaazz", "xxbaaz") → 3      0      X         
stringMatch("abc", "abc") → 2      0      X         
stringMatch("abc", "axc") → 0      0      OK         
stringMatch("hello", "he") → 1      0      X         
stringMatch("he", "hello") → 1      0      X         
stringMatch("h", "hello") → 0      1      X         
stringMatch("", "hello") → 0      0      OK         
stringMatch("aabbccdd", "abbbxxd") → 1      0      X         
stringMatch("aaxxaaxx", "iaxxai") → 3      0      X         
stringMatch("iaxxai", "aaxxaaxx") → 3      0      X         


How to fix and improve my code. Please advise
0
gudii9
Asked:
gudii9
  • 11
  • 7
  • 4
  • +1
3 Solutions
 
rrzCommented:
1)You must use String's equals method to compare the Strings. Don't use == to compare them.
2)You are comparing a substring from "a" with the same thing. You need to compare a substring from "a" to a substring from "b".    
3)You are comparing a substring length of 1.  But the challenge asks you compare substring length of 2.
4)You don't consider different lengths of input Strings. You could use Math.min method to find the shorter String length.
0
 
dpearsonCommented:
There are several problems with your code.

Compare to this code and see if you can spot  the differences?

Doug

	public int stringMatch(String a, String b) {
		int count=0;
                int len = Math.min(a.length(), b.length()) ;
		for(int i=0;i<len-1;i++){
		   if(a.substring(i,i+2).equals(b.substring(i,i+2)))
		      count++;
		}
		return count;
		  
		}

Open in new window

0
 
dpearsonCommented:
Oops - I see rrz posted largely the same thing (as text).  Apologies - my browser didn't update in time.

DOug
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
rrzCommented:
No problem, Doug.
0
 
gudii9Author Commented:
public int stringMatch(String a, String b) {
int count=0;
		for(int i=0;i<=a.length()-1&&i<=b.length()-1;i++){
		if(a.substring(i,i+2).equals(b.substring(i,i+2)))
		count++;
		}
		return count;
  
}

Open in new window


can I see both a and b lenth with && in the for loop as above. I still do not pass tests as above?
when to use == and when to use .equals? Please advise
0
 
gudii9Author Commented:
public int stringMatch(String a, String b) {
int count=0;
int len=Math.min(a.length(), b.length());
		for(int i=0;i<=len-1;i++){
		if(a.substring(i,i+2).equals(b.substring(i,i+2)));
		count++;
		}
		return count;
  
}


	

Open in new window


when i wrote as above i am getting index out of bound on many test cases.

Expected      Run            
stringMatch("xxcaazz", "xxbaaz") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X         
stringMatch("abc", "abc") → 2      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:4)      X         
stringMatch("abc", "axc") → 0      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:4)      X         
stringMatch("hello", "he") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:4)      X         
stringMatch("he", "hello") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:4)      X         
stringMatch("h", "hello") → 0      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:4)      X         
stringMatch("", "hello") → 0      0      OK         
stringMatch("aabbccdd", "abbbxxd") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 8 (line number:4)      X         
stringMatch("aaxxaaxx", "iaxxai") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X         
stringMatch("iaxxai", "aaxxaaxx") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X      

To me the above code is same as the code you posted. please advise

	public int stringMatch(String a, String b) {
		int count=0;
                int len = Math.min(a.length(), b.length()) ;
		for(int i=0;i<len-1;i++){
		   if(a.substring(i,i+2).equals(b.substring(i,i+2)))
		      count++;
		}
		return count;
		  
		}

Open in new window


your code as above is passing all tests
0
 
ozoCommented:
Do you understand the difference between < and <= ?
0
 
gudii9Author Commented:
yes i see the difference. why we should use .equals but not ==.

Till now i was using == for characters i believe. please advise
0
 
ozoCommented:
I did not say anything about ==
Neither of the examples in your http:#a40431871 comment use ==
0
 
gudii9Author Commented:
Do you understand the difference between < and <=

I understand the difference.

if i say i<4 it only looks till 3 i.e 0,1,2,3 not 4
if i say i<=4 then it look till 4 including 4 i.e 0,1,2,3,4
0
 
gudii9Author Commented:
I found one link which explained me the difference between == and equals clearly
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
0
 
gudii9Author Commented:
for(int i=0;i<=len-1;i++){

Open in new window


My code i should not have said as above.

for(int i=0;i<len-1;i++){

Open in new window

Above one is correct which does not go beyond the limit
0
 
rrzCommented:
Till now i was using == for characters

Yes, we use that shortcut.  The long way is to use the equals method in the Character class. Look at
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object) 
and run
public class Test {
	public static void main(String[] args) {
        char aChar = 'a';
        char bChar = 'b';
        Character aCharacter = new Character(aChar);
		if(aChar + 1 == bChar)System.out.println("Yes, aChar + 1 equals bChar");
        if(aCharacter.equals(aCharacter))System.out.println("Sure it does");        
	}
}          

Open in new window

The output is
>java Test
Yes, aChar + 1 equals bChar
Sure it does
You can see that using  == with char really is comparing int values. Look at
http://www.scism.lsbu.ac.uk/jfl/Appa/appa4.html   
to see values. You see value of 'a' is 97 and value of 'b' is 98.
when to use == and when to use .equals?
You can read at
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/   
and  
http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html   
       
You should use == to compare objects(refer to the same place in memory) or primitives(int value for example).
You should use String's equal method to compare the contents of each String.

If you look at API
https://docs.oracle.com/javase/7/docs/api/index-files/index-5.html   
You will see many equals methods. Most classes have a equals method that override the equals method of the Objects  class. See
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)   
where it says
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
But, the equals method in subclasses(like the String class) override the Object class equals method and compare contents or attributes that make sense for that class.
0
 
dpearsonCommented:
The general rule is:

Use == for primitives (double, int, char, boolean etc.)   <-- these types all start with a lowercase later
Use equals for objects (String, Object, Integer, etc.)      <-- these types all start with an uppercase later

If you call a method - check what it returns.

String x ;
x.substring(1,2)   <-- returns String so use equals to test
x.substring(1,2).equals("hello") ;

x.charAt(3)   <-- returns char so use ==
x.chatAt(3) == 'x' ;

Doug
0
 
rrzCommented:
Also, from one of the links I posted.
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
0
 
gudii9Author Commented:
>java Test
Yes, aChar + 1 equals bChar
Sure it does
we  got above highlighted output because 97+1=98 right(as 98 is the ordinal number of the character in the range 0 to 255 for 'b Lower case B' as attached from below link)?
http://www.scism.lsbu.ac.uk/jfl/Appa/appa4.html
so for char it is ideally better to use == as it is primitive. But practically i can use either == or equals  which does same thing functionally right. (== compares ordinal number of the character of aChar and bChar and .equals checks the content hence   if(aCharacter.equals(aCharacter))System.out.println("Sure it does"); results Sure it does. Ofcourse downside of using equals with char primitive is i have to cast primitive to object Character type as below  before hand right?(so better to use == itself to make coding easy while using char)
  Character aCharacter = new Character(aChar);
0
 
gudii9Author Commented:
 String letter = str.substring(i,i+1) ;
  if(i == 0 || i == str.length()-1 || !letter.equals("x"))
    sb.append(letter) ;

I see in above example x is character but they are using as string (within " " as "x", not they are not converting char to Character like Character xCharacter=new Character(x)) then using .equals similar to how they use .equals on Objects and String.
Which seems bit odd to me.
Please advise
0
 
rrzCommented:
we  got above highlighted output because 97+1=98 right(as 98 is the ordinal number of the character in the range 0 to 255 for 'b Lower case B' as attached from below link)?
Yes  
so for char it is ideally better to use == as it is primitive.
It is just easier.
i have to cast primitive to object Character type as below  before hand right?
That is not casting. We are using the constructor to create a new object.  It is known as boxing. You should also realize that there is a thing called autoboxing. See    
http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html       
So, we can also add the following line to my code.
if(aCharacter.equals(aChar))System.out.println("Sure it does, because of autoboxing!");

Open in new window

0
 
rrzCommented:
I see in above example x is character
No. You are comparing a String to a String. Just as Doug pointed out, the substring method returns a String.  The String class implements the CharSequence interface. See
https://docs.oracle.com/javase/7/docs/api/java/lang/CharSequence.html   
So, String  is a readable sequence of char values.  As Doug posted, some of String's method return char and some return String.
0
 
gudii9Author Commented:
!letter.equals("x")

i mistakenly thought letter is a 'char'.

As Doug posted, some of String's method return char and some return String.

I wonder where is the corresponding link. which string methods return char?
i see only charValue() method returns char and valueOf returns Character in below API as below

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object)

static Character      valueOf(char c)
Returns a Character instance representing the specified char value.
0
 
rrzCommented:
which string methods return char?
Sorry, I posted without looking at
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html 
I only see the method charAt and the method toCharArray which returns a char array.
0
 
gudii9Author Commented:
x.substring(1,2).equals("hello") ;

do we need to say above statement as below
(x.substring(1,2)).equals("hello") ;
please advise
0
 
ozoCommented:
No, because you can replace
(x.substring(1,2)).equals("hello")
with
false

If you had said
(x.substring(1,2)).equals("h")
then that could be replaced with
x.charAt(1)=='h'
0
 
gudii9Author Commented:
No, because you can replace
(x.substring(1,2)).equals("hello")
with
false

i was not clear on above. can you please elaborate


I was clear on below

If you had said
(x.substring(1,2)).equals("h")
then that could be replaced with
x.charAt(1)=='h'
0
 
ozoCommented:
A string of length 1 never equals a string of length 5.
0
 
dpearsonCommented:
x.substring(1,2).equals("hello") ;

do we need to say above statement as below
(x.substring(1,2)).equals("hello") ;
please advise

Yes - you can write the original expression
   x.substring(1,2).equals("hello")
as
   (x.substring(1,2)).equals("hello") ;

if that makes it clearer that the "x.substring(1,2)" part executes first and returns a value, which we then use "equals" on.

You can also write it as:
   String sub = x.substring(1,2) ;
   sub.equals("hello") ;

if that helps make it clearer.  They'll all produce the same results.

Doug
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 11
  • 7
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now