Home  >  Article  >  Java  >  Java determines whether a string contains the specified string

Java determines whether a string contains the specified string

尚
Original
2019-12-28 14:19:143941browse

Java determines whether a string contains the specified string

#indexOf(String s), if included, the returned value is the starting position of the substring in the parent string including the substring; if not included, the entire return value must be -1

package my_automation;

public class z_test {

    public static void main(String[] args) {
        String test = "This is test for string";
        System.out.println(test.indexOf("This")); //0
        System.out.println(test.indexOf("is")); //2
        System.out.println(test.indexOf("test")); //8
        System.out.println(test.indexOf("for")); //13
        System.out.println(test.indexOf("for string       "));//-1
        if (test.indexOf("This")!=-1){
            //"只要test.indexOf('This')返回的值不是-1说明test字符串中包含字符串'This',相反如果包含返回的值必定是-1"
            System.out.println("存在包含关系,因为返回的值不等于-1");     
        }else{    
            System.out.println("不存在包含关系,因为返回的值等于-1");
        }
        if (test.indexOf("this")!=-1){
            //"只要test.indexOf('this')返回的值不是-1说明test字符串中包含字符串'this',相反如果包含返回的值必定是-1"
            System.out.println("存在包含关系,因为返回的值不等于-1");   
        }else{ 
            System.out.println("不存在包含关系,因为返回的值等于-1");
        }  
    }
}

indexOf() usage:

Returns the position where the string string in indexof (string) first appears in the parent string in the character, starting from 0! There is no return of -1; it is convenient for judging and intercepting strings!

indexOf() definition and usage The indexOf() method returns the position where a specified string value first appears in the string.

Syntax stringObject.indexOf(searchvalue,fromindex)

Parameter Description searchvalue Required. Specifies the string value to be retrieved.

fromindex Optional integer parameter. Specifies the position in the string to begin searching. Its legal values ​​are 0 to - 1. If this parameter is omitted, the search will start from the first character of the string.

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Java determines whether a string contains the specified string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn