Indexof C# là gì

Java String indexOf[] method is used to find the index of a specified character or a substring in a given String. There are 4 variations of this method in String class:

The indexOf[] method signature

int indexOf[int ch]: It returns the index of the first occurrence of character ch in a given String.

int indexOf[int ch, int fromIndex]: It returns the index of first occurrence of character ch in the given string after the specified index fromIndex. For example, if the indexOf[] method is called like this str.indexOf[A, 20] then it would start looking for the character A in string str after the index 20.

int indexOf[String str]: Returns the index of string str in a particular String.

int indexOf[String str, int fromIndex]: Returns the index of string str in the given string after the specified index fromIndex.

All the above variations returns -1 if the specified char/substring is not found in the particular String.

Java String indexOf[] Method example

public class IndexOfExample{ public static void main[String args[]] { String str1 = new String["This is a BeginnersBook tutorial"]; String str2 = new String["Beginners"]; String str3 = new String["Book"]; String str4 = new String["Books"]; System.out.println["Index of B in str1: "+str1.indexOf['B']]; System.out.println["Index of B in str1 after 15th char:"+str1.indexOf['B', 15]]; System.out.println["Index of B in str1 after 30th char:"+str1.indexOf['B', 30]]; System.out.println["Index of string str2 in str1:"+str1.indexOf[str2]]; System.out.println["Index of str2 after 15th char"+str1.indexOf[str2, 15]]; System.out.println["Index of string str3:"+str1.indexOf[str3]]; System.out.println["Index of string str4"+str1.indexOf[str4]]; System.out.println["Index of hardcoded string:"+str1.indexOf["is"]]; System.out.println["Index of hardcoded string after 4th char:"+str1.indexOf["is", 4]]; } }

Output:

Index of B in str1: 10 Index of B in str1 after 15th char:19 Index of B in str1 after 30th char:-1 Index of string str2 in str1:10 Index of str2 after 15th char-1 Index of string str3:19 Index of string str4-1 Index of hardcoded string:2 Index of hardcoded string after 4th char:5

Another example of indexOf[] method

Lets take a simple example with a short string where we are finding the indexes of given chars and substring using the indexOf[] method.

public class JavaExample { public static void main[String[] args] { String str = "Java String"; char ch = 'J'; char ch2 = 'S'; String subStr = "tri"; int posOfJ = str.indexOf[ch]; int posOfS = str.indexOf[ch2]; int posOfSubstr = str.indexOf[subStr]; System.out.println[posOfJ]; System.out.println[posOfS]; System.out.println[posOfSubstr]; } }

Output:

PreviousNext

Video liên quan

Chủ Đề