【本節目标】
通過閱讀本節内容,你将了解到字元串拆分、截取、格式化相關的方法,并學會使用這些方法來對字元串進行相關的操作。
字元串拆分
在字元串處理的時候還提供有一種字元串拆分的處理方法,字元串的拆分操作主要是可以根據一個指定的字元串或者是一些表達式實作字元串的拆分,并且拆分完成的資料将以字元串數組的形式傳回。
No. | 方法名稱 | 類型 | 描述 |
---|---|---|---|
01 | public String[] split(String regex) | 普通 | 按照指定的字元串全部拆分 |
02 | public String[] split(String regex,int limit) | 按照指定的字元串拆分為指定個數,後面不拆了 |
範例:觀察字元串拆分處理
public class StringDemo{
public static void main(String args[]) {
String str = “hello world hello mldn” ;
String result [] = str.split(“ ”) ; //空格拆分
for (int x = 0 ; x < result.length ; x ++) {
System.out.println(result [x]) ;
}
}
}

圖一 執行結果一
除了可以全部拆分之外,,也可以拆分為指定的個數。
範例:拆分指定個數
public class StringDemo{
public static void main(String args[]) {
String str = “hello world hello mldn” ;
String result [] = str.split(“ ” , 2) ; //空格拆分
for (int x = 0 ; x < result.length ; x ++) {
System.out.println(result [x]) ;
}
}
}
圖二 執行結果二
但是在進行拆分的時候有可能會遇見拆不了的情況,這種時候最簡單的了解就是使用“\”進行轉義。
public class StringDemo{
public static void main(String args[]) {
String str = “192.168.1.2” ;
String result [] = str.split(“.”) ; //.拆分
for (int x = 0 ; x < result.length ; x ++) {
System.out.println(result [x]) ;
}
}
}
圖三 執行結果三
public class StringDemo{
public static void main(String args[]) {
String str = “192.168.1.2” ;
String result [] = str.split(“\\.”) ; //.拆分
for (int x = 0 ; x < result.length ; x ++) {
System.out.println(result [x]) ;
}
}
}
圖四 執行結果四
對于拆分與替換的更多操作後面會進行更多的講解說明。
字元串截取
從一個完整的字元串之中截取出子字元串,對于截取操作有兩個方法。
public String substring(int beginIndex) | 從指定索引到結尾 | ||
public String substring(int beginIndex,int endIndex) | 截取指定索引範圍中的子字元串 |
範例:觀察字元串截取操作
public class StringDemo{
public static void main(String args[]) {
String str = “www.mldn.cn” ;
System.out.println(str.substring(4)) ; //mldn.cn
System.out.println(str.substring(4 , 8)) ; //mldn
}
}
在實際的開發之中,有些時候的開始或結束索引往往都是通過indexOf()方法計算得來的。
範例:觀察截取
public class StringDemo{
public static void main(String args[]) {
//字元串結構:“使用者id-photo-姓名.字尾”
String str = “mldn-photo-張三.jpg” ;
int beginIndex = str.indexOf(“-” ,str.indexOf(“photo”)) + 1 ;
int endIndex = str.lastIndexOf(“.”) ;
System.out.println(str.substring(beginIndex,endIndex)) ; //張三
}
}
在以後的實際開發之中,這種通過計算來确定索引的情況非常常見。
字元串格式化
從JDK1.5開始為了吸引更多的傳統開發人員,Java提供有了格式化資料的處理操作。類似于C語言之中的格式化輸出語句。可以利用占位符實作資料的輸出,對于占位符而言,常用的:字元串(%s)、字元(%c)、整數(%d)、小數(%f)等來描述。
public static String format(String format,各種類型... args) | 根據指定結構進行文本格式化顯示 |
範例:觀察格式化處理
public class StringDemo{
public static void main(String args[]) {
String name = “張三” ;
int age = 18 ;
double score = 98.765321 ;
String str = String.format(“姓名:%s、年齡:%d、成
績:%5.2f。”,name ,age ,score) ;
System.out.println(str) ;
}
}
圖五 執行結果五
這種格式化的輸出操作算是String 的一個附加功能。
想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。
本内容視訊來源于
阿裡雲大學 下一篇:領略String完美側顔-其他操作方法 | 帶你學《Java面向對象程式設計》之三十五 更多Java面向對象程式設計文章檢視此處