A summary of the lookup methods for substrings in Java strings

  • 2020-04-01 04:18:22
  • OfStack

There are four ways to find a neutron string in a string in Java, as follows:
Int indexOf(String STR) : returns the indexOf the first occurrence of the specified substring in this String.
Int indexOf(String STR, int startIndex) : returns the indexOf the first occurrence of the specified substring in the specified String, starting at the specified index.
Int lastIndexOf(String STR) : returns the index of the specified substring that appears on the rightmost side of this String.
Int lastIndexOf(String STR, int startIndex) : search backward from the specified index to return the index of the specified substring that last appeared in this String.

Usage description of indexof()


indexof()

Returns the character position of the first occurrence of a substring in a String object.


string.indexOf(subString[, startIndex])

parameter


string

Will be options. String object or literal.

SubString required option.

The substring to look for in the String object.

StarIndex is optional.

The integer value indicates the index in the String object for which the search is started. If omitted, look at the beginning of the string.

instructions
The indexOf method returns an integer value indicating the starting position of the substring inside the String object. If no substring is found, -1 is returned.

If startindex is negative, startindex is treated as zero. If it is larger than the largest character position index, it is considered the largest possible index.

Perform the lookup from left to right. Otherwise, the method is the same as lastIndexOf.

The sample
The following example illustrates the use of the indexOf method.


function IndexDemo(str2){ 
var str1 = "BABEBIBOBUBABEBIBOBU" 
var s = str1.indexOf(str2); 
return(s); 
}

Java looks for the number of substrings contained in a string
1. Use the method of indexof:


public class Test11 
{

 private static int counter = 0;
 
 public static void main(String[] args) 
 {
 String str ="sdSS**&HGJhadHCASch& ^^";
 int i = stringNumbers(str);
 System.out.println(i);
 }
 
 public static int stringNumbers(String str)
 {
 if (str.indexOf("java")==-1)
 {
 return 0;
 }
 else if(str.indexOf("java") != -1)
 {
 counter++;
 stringNumbers(str.substring(str.indexOf("java")+4));
 return counter;
 }
 return 0;
 }
}

2. If the substring is not a string with the same beginning and end, it can also be implemented as follows:


if(str.indexOf("java") != -1)
 {
 String[] str1 = str.split("java");
 System.out.println(str1.length-1);
 }
 else 
 {
 System.out.println(0);
 }


Related articles: