在Java中,如何在字串中查找片語?
此示例顯示了如何使用indexOf()
方法在String
對象中搜索單詞,該方法返回字串中的單詞的位置索引(如果找到)值。 否則返回-1
。
package com.zaixian;
public class SearchStringEmp {
public static void main(String[] args) {
String strOrig = "Hello, Sukida";
int intIndex = strOrig.indexOf("Su");
if (intIndex == -1) {
System.out.println("Su not found");
} else {
System.out.println("Found Su at index : " + intIndex);
}
}
}
執行上面示例代碼,得到以下結果 -
Found Su at index : 7
示例2
此示例顯示了如何在String
對象中搜索單詞
package com.zaixian;
public class SearchStringEmp2 {
public static void main(String[] args) {
String text = "This is my dog, it is name PigPig";
System.out.print("Is found the word ? " + text.contains("dog"));
}
}
執行上面示例代碼,得到以下結果 -
Is found the word ? true