Java String indexOf()The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string. SignatureThere are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:
Parametersch: It is a character value, e.g. 'a' fromIndex: The index position from where the index of the char value or substring is returned. substring: A substring to be searched in this string. ReturnsIndex of the searched string or character. Internal Implementation Java String indexOf() Method ExampleFileName: IndexOfExample.java Test it NowOutput: 2 8 5 3 We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example. FileName: IndexOfExample5.java Output: In the String: Welcome to JavaTpoint The 'o' character has come 3 times Java String indexOf(String substring) Method ExampleThe method takes substring as an argument and returns the index of the first character of the substring. FileName: IndexOfExample2.java Test it NowOutput: index of substring 16 Java String indexOf(String substring, int fromIndex) Method ExampleThe method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex. FileName: IndexOfExample3.java Test it NowOutput: index of substring 16 index of substring -1 Java String indexOf(int char, int fromIndex) Method ExampleThe method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex. FileName: IndexOfExample4.java Test it NowOutput: index of char 17 Next TopicJava String intern |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India