Usage and example of the indexOf method of the String class

The function and return value of the indexof method of the String class:

img

Today, I will focus on reviewing here, I hope it can be helpful to you:

indexOf(int,ch)

First look at the first indexOf, its return value is int, and looking at its parameters (int, ch) means that the user can give the parameter an int value represented by a 'char' character, and then find the character in the character from front to back The index of the first occurrence in the string, of course, we can't remember the value of each char, so we use String s=abcdef; int i=s.indexOf('d');

This method is enough, the char type will be automatically promoted to the int type, and it should be noted that if the return value is -1, it means that the index is out of bounds;

indexOf(int ch,int,fromIndex)

This method is to find the index of the first occurrence of the returned character in the string from the specified position, such as "woaizhongguo" indexOf('o', 2), the return value is 6 instead of 1, not 11;

indexOf(Sting str)

This method is basically similar to the previous one, except that it gives a substring in the parameter, and then returns the index of the first occurrence of the substring in the string, such as "woaixuexi" to check "ai" The index position where this substring appears in the entire string is returned as 2

**indexOf(String str, int fromIndex)** This method is not repeated

lastIndexOf(int ch)

This method is also the opposite of indexof. It finds the index of the last occurrence of the returned character in the string from back to front, that is to say, when looking for the index, it is searched backwards, but the return value is returned in the positive index order. For example, "woaiwo" using lastindexof to find 'w' returns 4 instead of 1

lastIndexOf(int ch,fromindex)

This method means to find the index of the last occurrence of the character in this string from the specified index from the back to the front. For example, if the specified index is 7, then the index before 7 is found for the first time and the index value is returned.

substring(int begjin): intercepts the string from a custom position until the end of the default return value is string

substring (int begin, int end) intercepts the string from the specified position to the end of the specified position string contains the head but not the tail

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/123594366