首頁  >  文章  >  Java  >  java判斷字串是否包含指定字串

java判斷字串是否包含指定字串

尚
原創
2019-12-28 14:19:143936瀏覽

java判斷字串是否包含指定字串

indexOf(String s)的使用,如果包含,傳回的值是包含該子字串在父類別字串中起始位置;如果不包含必定全部傳回值為-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()的用法:

返回字元中indexof(string)中字符串string在父字串中首次出現的位置,從0開始!沒有回傳-1;方便判斷和截取字串!

indexOf()定義和用法indexOf() 方法可傳回某個指定的字串值在字串中首次出現的位置。

語法stringObject.indexOf(searchvalue,fromindex)

參數 描述searchvalue 必要。規定需檢索的字串值。

fromindex 可選的整數參數。規定在字串中開始檢索的位置。它的合法取值是 0到 - 1。如省略該參數,則將從字串的首字開始檢索。

更多java知識請關注java基礎教學欄。

以上是java判斷字串是否包含指定字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn