Use indexOf () to match a string
Returns the first occurrence of a substring in a String object.
StrObj. indexOf (subString [, startIndex])
Parameters
StrObj
Required. String object or text.
SubString
Required. The substring to be searched in the String object.
StarIndex
Optional. This integer indicates the index in the String object. If it is omitted, it is searched from the beginning of the string.
Description
The indexOf method returns an integer indicating the starting position of the substring in the String object. If no substring is found,-1 is returned.
If startindex is negative, startindex is treated as zero. If it is larger than the index at the largest character location, it is regarded as the largest possible index.
Public class MainClass {
Public static void main (String [] arg ){
String str = "abcde ";
Int index = 0;
Index = str. indexOf ('C ');
System. out. println (index );
}
}
Instance 2
Public class MainClass {
Public static void main (String [] arg ){
String str = "abcdea ";
Int index = 0;
Index = str. lastIndexOf ('A ');
System. out. println (index );
}
}
Searches for the position of the specified character string.
Public class MainClass {
Public static void main (String [] arg ){
String str = "abcdea ";
Int startIndex = 3;
Int index = 0;
Index = str. indexOf ('A', startIndex );
System. out. println (index );
}
}
End of the string
Public int lastIndexOf (String str, int fromIndex)
// Start searching backward from the specified index and return the index of the last occurrence of the specified sub-string in this string.
// K <= Math. min (fromIndex, str. length () & this. startsWith (str, k)
// Find the last position of str in String! If the location is <= fromIndex, return-1. Otherwise, return-1.
Your scenario is:
// The last occurrence of One in banner is at 9
// And 9 <10, so 9 is returned.
Public class MainClass {
Public static void main (String [] arg ){
String str = "abcdeabcdef ";
Int index = 0;
Index = str. lastIndexOf ("AB ");
System. out. println (index );
}
}