方法 | 描述 |
---|---|
String substring(int beginIndex, int endIndex) | 回傳從 beginIndex 到 endIndex 之間的子字串 |
String substring(int beginIndex) | 回傳從 beginIndex 到結尾的子字串 |
舉例如下
class SubstringDemo { public static void main(String[] args) { String a = "Imagination is more important than knowledge."; String b = "He who has hope has everything."; String c = "台上一分鐘,台下十年功。"; System.out.println(a.substring(0, 15)); System.out.println(b.substring(20)); System.out.println(c.substring(3, 6)); } } /* 《程式語言教學誌》的範例程式 http://pydoing.blogspot.com/ 檔名:SubstringDemo.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */
編譯後執行,結果如下
中英文術語對照 | |
---|---|
類別 | class |
方法 | method |
字串 | string |
參考資料
http://download.oracle.com/javase/tutorial/java/data/strings.html
http://download.oracle.com/javase/tutorial/java/data/converting.html
http://download.oracle.com/javase/tutorial/java/data/manipstrings.html
http://download.oracle.com/javase/tutorial/java/data/comparestrings.html
http://download.oracle.com/javase/7/docs/api/java/lang/String.html
http://download.oracle.com/javase/tutorial/java/data/strings.html
http://download.oracle.com/javase/tutorial/java/data/converting.html
http://download.oracle.com/javase/tutorial/java/data/manipstrings.html
http://download.oracle.com/javase/tutorial/java/data/comparestrings.html
http://download.oracle.com/javase/7/docs/api/java/lang/String.html
4 則留言:
冒昧建議:
String substring(int beginIndex
建議改為 int offset
理由:依據 java 線上手冊
java.lang.String.substring(int offset, int endIndex)
簡單說 offset 是從0開始,index是從1開始
否則無法解釋
String str ='ABCDE'
str.substring(4,5)==> 可以得到 E
那個 5 是甚麼意思
提供您參考,謝謝
這裡的參數名稱直接用 Java 官方的 reference
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
不知道「 java 線上手冊」是指哪裡的?
str.substring(4,5) 取得索引值 4 到 5 之間的子字串,簡單說就是從 4 開始但不包含 5 ,因此得到 "E" ,文內說明可能沒有很清楚。
另外單引號為字元,雙引號為字串,字元跟字串是不同的喔!
^_^
From the Java Doc, it indicated
IndexOutOfBoundsException will be thrown by the JVM - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Since length of the String str ='ABCDE' is 5, so no exception will be thrown when endIndex is 5.
Nice post and discussion and hope this help.
實用!
張貼留言