1

For a string say, String str = "abc" both str.indexOf("a") and str.indexOf("") return 0. Is this behaviour valid?

6
  • 2
    possible duplicate of Java String.indexOf and empty Strings Commented Jan 2, 2015 at 1:35
  • What do you mean with valid? Do you imply there isn't a sequence of 0 characters at the very start of the string? Commented Jan 2, 2015 at 1:45
  • @Robert, My thought was suppose the search pattern is from an external source and let the pattern be "empty string". Now if I try to see the matched part I get first character instead of empty string. Commented Jan 2, 2015 at 1:54
  • @ViswanadhKumarReddyVuggumud Oh, but the matched part always equals the pattern. In particular the pattern and the matched part are of the same length. So you always have to check the length of the pattern, it might also be longer than 1 character. Commented Jan 2, 2015 at 1:59
  • @Robert I agree, not that it is serious but my point is it would make have made much better sense if the other way of finding the matching part is also true :) Commented Jan 2, 2015 at 2:08

5 Answers 5

11

If only there was some place where they document behaviour of methods.

indexOf(string)

Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which:

this.startsWith(str, k)

startsWith(string)

true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

Sign up to request clarification or add additional context in comments.

Comments

3

Yes. The conceptual reason is pretty similar as adding 0 in math. So ""+"a"+"bc" = "abc" = ""+"a"+"b"+""+"c".

Comments

1

The return value of String.indexof("") is 0, or the starting index, when you pass in an empty string because the empty string "" is indeed located there. Think of "abc" as "" + "abc".

Otherwise, please refer to this documentation:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)

indexOf "returns:the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur."

Therefore, str.indexOf("a") returns 0.

Comments

0

Think of it as

"" +"abc"="abc"

basically

"abc" is ""+"abc"

Comments

0

An empty string does in fact exist in any string that is not null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.