Last Updated:

Find a character in a string [ Java ]

How to find a substring in a string

 

Let's say you have the string "hello world" and you want to know if it contains the substring "world". Using the String.indexOf() method, you can find out the position of a substring in a string:

 

String str = "hello world";
System. out. println(str. indexOf("world"));
 

Console Output:

6

Thus, "hello" begins with the 6th position in the line "hello world". Note that numbering starts from zero, not one. Thus, str.indexOf("hello") will output zero to the console:

 

System. out. println(str. indexOf("hello")); // 0

If the specified character combination is not present in the search string, the indexOf method will return -1:

 

System. out. println(str. indexOf("hi")); // -1

Sample source code

 

package en. javalessons. strings;
 
public class IndexOf {
public static void main(String[] args) {
String str = "hello world";
System. out. println(str. indexOf("world"));
 
System. out. println(str. indexOf("hello")); // 0
 
System. out. println(str. indexOf("hi")); // -1
}
}

Resume

 

In this article, we learned how to find the position of a substring in a row.

The indexOf method allows you to find the position of a character in a string.