• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

indexOf

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello, please take a look at this code:
1 class strings
2 {
3 public static void main(String arg[])
4 {
5 if("String".indexOf("S",-10) ==0)
6 {
7 System.out.println("Equal");
8 }
9 else
10 {
11 System.out.println("Not Equal");
12 }
13 }
14 }
What does the indexOf method do, how do we use it, and how does the above code work?
Thank You,
Kamil
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is an interesting snippet. The method indexOf() returns a char from the index position or an int from the char position. Therefore, "String" => 012345
indexOf(char('S'), begin search fromIndex(-10))
if("String".indexOf("S",-10)==0) // Will (0,-10)==0?
{ // Run the code and find out!
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
Hope that helps a little,
Percy
 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
5 if("String".indexOf("S",-10) ==0)
if the second argument is negative value it is treated as 0. So the entire String is searched and it returns 0 because the indexOf "S" is 0.
0==0 is true so it prints Equals.


From API
public int indexOf(String str,
int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k such that:
this.startsWith(str, k) && (k >= fromIndex)

is true.
There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.


Vanitha.
 
reply
    Bookmark Topic Watch Topic
  • New Topic