1. 程式人生 > 其它 >Java String類中的startsWith()、endsWith()

Java String類中的startsWith()、endsWith()

Java String類中的startsWith()、endsWith()

1、startsWith() 方法用於檢測字串是否以指定的字首開始。

語法

public boolean startsWith(String prefix, int toffset)

或

public boolean startsWith(String prefix)

引數

  • prefix-- 字首。

  • toffset-- 字串中開始查詢的位置。

返回值

如果字串以指定的字首開始,則返回 true;否則返回 false。

例項

public class Test {
    public static
void main(String args[]) { String str = new String("www.runoob.com"); System.out.print("返回值 :" ); System.out.println(str.startsWith("www") ); System.out.print("返回值 :" ); System.out.println(str.startsWith("runoob") ); System.out.print("返回值 :" ); System.out.println(str.startsWith(
"runoob", 4) ); } }

以上程式執行結果為:

 返回值 = true

  返回值 = false

 返回值 = true

2、endsWith()方法用於檢測字串是否以指定的字尾結束。

語法

public boolean endsWith(String suffix)
 
引數
suffix -- 指定的字尾。
 
返回值
如果引數表示的字元序列是此物件表示的字元序列的字尾,則返回 true;否則返回 false。注意,如果引數是空字串,或者等於此 String 物件(用 equals(Object) 方法確定),則結果為 true

例項

public class
Test { public static void main(String args[]) { String str = new String("菜鳥:www.runoob.com"); System.out.println("返回值 = " + str.endsWith( "runoob" )); System.out.println("返回值 = " + str.endsWith( "com" )); } }

以上程式執行結果為:

 返回值 = false

 返回值 = true