更新時間:2022-11-07 11:04:43 來源:動力節點 瀏覽1765次
Java字符串split方法是什么?動力節點小編來告訴大家。
將此字符串拆分為給定的regular expression(正則表達式)匹配
參數:regex–分割正則表達式
結果:將字符串按分隔符分為字符串數組。
注意:
如果字符串中的regex后面字符也是regex,后面每有一個regex,字符串數組中就會在對應的位置多一個空字符串。但如果空字符串在末尾,字符串數組就會將它舍棄。
public class test {
public static void main(String[] args) {
String str = "1,,2,3,4,,,,";
String[] s = str.split(",");
for (String word : s) {
System.out.println(word + "%");
}
}
}
從結果中我們可以看出第二個逗號作為空字符串在字符串數組中存在,而字符串str末尾的逗號都被舍棄。
當regex為①( ②[ ③{ ④/ ⑤^ ⑥- ⑦$ ⑧¦ ⑨} ⑩] ? ) ?? ?* ?+ ?.等這些特殊字符時,需要在前面加上\\進行轉義。
public class test {
public static void main(String[] args) {
String str = "1..2.3.4....5.6...";
String[] s = str.split("\\.");
for (String word : s) {
System.out.println(word + "%");
}
}
}
從上述結果可以看出.需要轉義字符形成\\.才能對字符串分割。而且輸出結果也驗證了第一點regex后面的每個regex對應字符串數組中的空字符串,末尾的部分舍棄。
將此字符串拆分為給定的regular expression(正則表達式)匹配
參數:
regex–分割正則表達式;
limit–影響字符串數組的長度
limit > 0 : regex的匹配模式將最多被應用limit - 1次,數組的長度不會超過limit,數組的最后一項有可能包含所有超出最后匹配的regex。
limit = 0 : 與不帶參數limit的split方法相同,結尾的空字符串被舍棄。
limit < 0 : 匹配模式將盡可能多的使用,而且字符串數組可以是任意長度。
結果:將字符串按分隔符分為字符串數組。
String str = "3..2.1.1....1.6...";
當regex = "1"時,
public class test {
public static void main(String[] args) {
String str = "3**2*1*1****1*6***";
int[] limitArr = {0, 2, 5, -2};
for (int limit : limitArr) {
String[] s = str.split("1", limit);
System.out.println("limit = " + limit + " : " + Arrays.toString(s));
}
}
}
當regex = "\\*"時,
public class test {
public static void main(String[] args) {
String str = "3**2*1*1****1*6***";
int[] limitArr = {0, 2, 5, -2};
for (int limit : limitArr) {
String[] s = str.split("\\*", limit);
System.out.println("limit = " + limit + " : " + Arrays.toString(s));
}
}
}
leetcode–1078. Bigram 分詞
這道題目很簡單,直接上代碼:
public String[] findOcurrences(String text, String first, String second) {
List<String> res = new ArrayList<>();
String[] words = text.split(" ");
for (int i = 0; i < words.length - 2; i++) {
if (words[i].equals(first) && words[i + 1].equals(second))
res.add(words[i + 2]);
}
return res.toArray(new String[0]);
}
注意:
split方法字符串進行分割;
toArray(new String[0])將List轉換為數組;
以上就是關于“Java字符串split方法介紹”,大家如果想了解更多相關知識,不妨來關注一下本站的Java在線學習,里面的課程內容從入門到精通,細致全面,很適合0基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習