String indexOf returns the index of the given String for specified conditions. String indexOf method can be used with multiple types of parameters as shown below
1 2 3 4 |
public int indexOf(int ch) public int indexOf(int ch,int fromIndex) public int indexOf(String str) public int indexOf(String str,int fromIndex) |
1. int indexOf(int ch) returns the index of the first occurrence of the specified character.
2. int indexOf(int ch,int fromIndex) returns the index of the first occurrence of the specified character starting from the “fromIndex”
3. int indexOf(String str) returns the index of the first occurrence of the specified String.
4. int indexOf(String str,int fromIndex) returns the index of the first occurrence of the specified String from the “fromIndex”.
String indexOf example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kscodes.sampleproject; public class StringIndexOfExample { public static void main(String[] args) { String testStr1 = "This is test String for IndexOf example"; System.out.println("Using indexOf(int) finding index of 'S' :: " + testStr1.indexOf('S')); System.out.println("Using indexOf(int,int) finding index of 'e' after 20 Charatcers :: " + testStr1.indexOf('e', 20)); System.out.println("Using indexOf(String) finding index of 'test' :: " + testStr1.indexOf("test")); System.out.println("Using indexOf(int) finding index of 'ex' after 15 characters :: " + testStr1.indexOf("ex",15)); System.out.println("-----------------------"); System.out.println("Using indexOf(String) finding index of '1234356' :: " + testStr1.indexOf("123456")); } } |
Output
1 2 3 4 5 6 |
Using indexOf(int) finding index of 'S' :: 13 Using indexOf(int,int) finding index of 'e' after 20 Charatcers :: 27 Using indexOf(String) finding index of 'test' :: 8 Using indexOf(int) finding index of 'ex' after 15 characters :: 27 ----------------------- Using indexOf(String) finding index of '1234356' :: -1 |
Please Note:
Before performing any operation on any dynamically generated String, check if the String is not null.
Else a NullPointerException is thrown.
Before performing any operation on any dynamically generated String, check if the String is not null.
Else a NullPointerException is thrown.
Reference
1. String API