Using the standard loop, I compared a substring to a string value like this:
if (str.substring(i, i+3) == "dog" ) dogcount++;
and it broke the iteration. After the first increment, no further instances of "dog" would be detected.
So I used substring.equals, and that worked:
if (str.substring(i, i+3).equals("dog")) dogcount++;
My question is, why? Just seeking better understand, thx.
You should use equals()
instead of ==
to compare two strings.
s1 == s2
returns true if both strings point to the same object in memory. This is a common beginners mistake and is usually not what you want.
s1.equals(s2)
returns true if both strings are physically equal (i.e. they contain the same characters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With