Finding a Character or a Substring

The String class provides several overloaded indexOf and lastIndexOf methods to find a character or a substring in a string.
Method syntax Return type Description
+indexOf(ch:char) int Returns the index of the first occurrence of ch in the string. Returns-1 if not matched.
+indexOf(ch:char,formIndex:int) int Return the index of the first occurrence of ch after fromIndex in the string. Return -1 in not matched.
+indexOf(str:string) int Returns the index of the first occurrence of string s in this string. Returns-1 if not matched.
+indexOf(str:string,fromIndex:int) int Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched.
+lastIndexOf(ch:char) int Returns the index of the last occurrence of ch in the string. Returns-1 if not matched. 
+lastIndexOf(ch:char,fromIndex:int) int Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched. 
+lastIndexOf(str:String) int Returns the index of the last occurrence of string s. Returns -1 if not matched. 
+lastIndexOf(str:String,formIndex:Int) int Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched.

"Welcome to Java".indexOf('W');                         returns 0 
"Welcome to Java".indexOf('o');                           returns 4 
"Welcome to Java".indexOf('o', 5);                       returns 9
"Welcome to Java".indexOf("come");                  returns 3
"Welcome to Java".indexOf("Java", 5);                returns 11 
"Welcome to Java".indexOf("java", 5);               returns -1
"Welcome to Java".lastIndexOf('W');                   returns 0 
"Welcome to Java".lastIndexOf('o');                    returns 9 
"Welcome to Java".lastIndexOf('o', 5);                 returns 4
 "Welcome to Java".lastIndexOf("come");            returns 3 
"Welcome to Java".lastIndexOf("Java", 5);          returns -1 
"Welcome to Java".lastIndexOf("Java");             returns 11

Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons