| Author |
Confusion about indexOf method
|
Rd Dari
Ranch Hand
Joined: Feb 22, 2010
Posts: 194
|
|
Hi,
There is a snippet of code:
Options of the output are:-
and the output of the code is : -1
How it is working please explain it.
Thank you
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
|
String's indexOf method returns -1 if the substring is not found. I don't see a (lowercase) 'f' in "Foolish".
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Rd Dari
Ranch Hand
Joined: Feb 22, 2010
Posts: 194
|
|
ok but if there is
then what output should be:
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
Try it and find out.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Sergey Baranov
Greenhorn
Joined: Aug 27, 2005
Posts: 18
|
|
indexOf
public int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that:
this.startsWith(str, k)
is true.
Parameters:
str - any string.
Returns:
if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
|
Sergey Baranov
|
 |
Rd Dari
Ranch Hand
Joined: Feb 22, 2010
Posts: 194
|
|
Hi Wouter Oet ,
I run this program and output is 0.
But actually I am not understanding that how it works so please give me some explanation which will helpful for me to understand it easily.
Thanks in advance....
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9939
|
|
the positions of "Foolish" are counted like this:
F -> 0
o -> 1
o -> 2
l -> 3
i -> 4
s -> 5
h -> 6
So, "Fool" matches starting at the 0th position.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
The indexOf() method searches in the string that you call it on, where the string that you pass as an argument appears - exactly what the API documentation that Sergey quoted says.
The word "Fool" appears in the string "Foolish boy." at the beginning - index 0.
Can you explain in more detail what exactly you don't understand about that?
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Rd Dari
Ranch Hand
Joined: Feb 22, 2010
Posts: 194
|
|
Yes Jasper,
In actual I was confused that how it matches to subString but Thank you of all you for giving me a good explanation I understand now this so thank you once again...............
|
 |
 |
|
|
subject: Confusion about indexOf method
|
|
|