s.indexOf( sub )
returns:
the (integer) index (position) of the first occurence
of the substring sub in string s
-1 if substring sub is not found in string s
|
Examples:
0123456789...
"Hello World, Bye World".indexOf( "World" ) returns: 6
0123456789012345678901
"Hello World, Bye World".indexOf( "By" ) = 13
0123456789012345678901
"Hello World, Bye World".indexOf( "by" ) = -1
|
s.lastIndexOf( sub )
returns:
the (integer) index (position) of the last occurence
of the substring sub in string s
-1 if substring sub is not found in string s
|
Examples:
0123456789012345678901
"Hello World, Bye World".lastIndexOf( "World" ) returns: 17
|
Java program that illustrates indexOf() and lastIndexOf():
public class IndexOf1
{
public static void main( String[] args )
{
String s;
int i;
// 0123456789012345678901
s = "Hello World, Bye World";
i = s.indexOf( "World" );
System.out.println( " 0123456789012345678901");
System.out.println( "\"" + s + "\""
+ ".indexOf( \"World\" ) = " + i );
i = s.indexOf( "By" );
System.out.println( " 0123456789012345678901");
System.out.println( "\"" + s + "\""
+ ".indexOf( \"By\" ) = " + i );
i = s.indexOf( "by" );
System.out.println( " 0123456789012345678901");
System.out.println( "\"" + s + "\""
+ ".indexOf( \"by\" ) = " + i );
/* ================================================= */
i = s.lastIndexOf( "World" );
System.out.println( " 0123456789012345678901");
System.out.println( "\"" + s + "\""
+ ".lastIndexOf( \"World\" ) = " + i );
}
}
|
Output:
0123456789012345678901
"Hello World, Bye World".indexOf( "World" ) = 6
0123456789012345678901
"Hello World, Bye World".indexOf( "By" ) = 13
0123456789012345678901
"Hello World, Bye World".indexOf( "by" ) = -1
|
How to run the program:
|