1 2 3 4 5 6 7 8 9 10 11 | public class StringIndexOf { public static void main(String[] args) { String sentence = "This is a ball. its color is black"; System.out.println("first index of \"l\" is " + sentence.indexOf('l')); System.out.println("first index of \"l\" after position 15 is " + sentence.indexOf('l', 15)); int i = sentence.lastIndexOf('l'); System.out.println("last index of \"l\" is " + i); System.out.println("last index of \"l\" is " + sentence.lastIndexOf('l',23)); } } |
indexOf(int ch) returns int value that is the first occurrence of specified character in given string. Counting start from 0. If character not found it returns -1
indexOf(int ch, int fromIndex) returns int value that is the first occurrence of specified character in given string after specified position. If character not found it returns -1.
lastIndexOf(int ch)return int value that is last occurrence of specified character.
public int lastIndexOf(int ch,int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index