古詩詞大全網 - 成語查詢 - JAVA中如何判斷壹個字符串是否為另壹個字符串的子串

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");

}?

}

擴展資料

java string中indexOf()常用用法

Java中字符串中子串的查找***有四種方法,如下:

1、int indexOf(String str) :返回第壹次出現的指定子字符串在此字符串中的索引。

2、int indexOf(String str, int startIndex):從指定的索引處開始,返回第壹次出現的指定子字符串在此字符串中的索引。

3、int lastIndexOf(String str) :返回在此字符串中最右邊出現的指定子字符串的索引。

4、int lastIndexOf(String str, int startIndex) :從指定的索引處開始向後搜索,返回在此字符串中最後壹次出現的指定子字符串的索引。

public class Test {

public static void main(String[] args) {

String s = "xXccxxxXX";

// 從頭開始查找是否存在指定的字符 //結果如下

System.out.println(s.indexOf("c")); //2

// 從第四個字符位置開始往後繼續查找,包含當前位置

System.out.println(s.indexOf("c", 3));? //3

//若指定字符串中沒有該字符則系統返回-1

System.out.println(s.indexOf("y")); //-1

System.out.println(s.lastIndexOf("x")); //6

System.out.println(s.indexOf(120,2));? //4

? System.out.println(s.indexOf('x',2));? //4? 120是x的ASCII編碼

}

}