In Java, an string class is a series of characters that are interpreted literally by a script. In order to preserve a number of components, often letters, a string is represented as a byte (or term) range information structure. Other kinds and configurations of sequence (or array) information can also be designated by the sequence, such as more generalised arrays.
Numerous methods, including compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), and substring(), are available in the Java String class.
To know more about String Class in java read the complete article.
String IndexOf() Method:
The Java String indexOf() method is used to get the index of the first instance of a condition that is stated in the method’s parameters. The position of the first occurrence of the provided character(s) in a string is returned by the indexOf() function.
The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java.These methods help us to perform operations on String objects such as trimming, concatenating, converting, comparing, replacing strings etc.
The index of the first occurrence of the provided substring is returned by the indexOf() function of the Java StringBuffer class.
Returns The index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
Note: If a character with value ch occurs in the character sequence represented by this String object, then the index of the first such occurrence is returned.
public class Main {
public static void main(String[] args) {
String myStr = "Hello PrepInsta Prime is a learning Platform.";
System.out.println(myStr.indexOf("I"));
}
}
Output
10
Explanation:Here the output comes is 10, because first occurrence of the letter "I" in a string, starting the search at starting position.
Example 3: Find the occurrence of the letter using IndexOf() Method.
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("PrepInsta is best Platform to learn java");
System.out.println("string: " + sb);
System.out.println("Index of substring abc: " + sb.indexOf("abc",0));
System.out.println("Index of substring point: " + sb.indexOf("point",20));
}
}
Output
string: PrepInsta is best Platform to learn java
Index of substring abc: -1
Index of substring point: -1
Explanation:Here the output comes returns -1 if no such mention substring found after mention index.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment