更新時間:2022-11-07 11:04:43 來源:動力節(jié)點 瀏覽1604次
Java字符串split方法是什么?動力節(jié)點小編來告訴大家。
將此字符串拆分為給定的regular expression(正則表達式)匹配
參數(shù):regex–分割正則表達式
結(jié)果:將字符串按分隔符分為字符串?dāng)?shù)組。
注意:
如果字符串中的regex后面字符也是regex,后面每有一個regex,字符串?dāng)?shù)組中就會在對應(yīng)的位置多一個空字符串。但如果空字符串在末尾,字符串?dāng)?shù)組就會將它舍棄。
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 + "%");
}
}
}
從結(jié)果中我們可以看出第二個逗號作為空字符串在字符串?dāng)?shù)組中存在,而字符串str末尾的逗號都被舍棄。
當(dāng)regex為①( ②[ ③{ ④/ ⑤^ ⑥- ⑦$ ⑧¦ ⑨} ⑩] ? ) ?? ?* ?+ ?.等這些特殊字符時,需要在前面加上\\進行轉(zhuǎn)義。
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 + "%");
}
}
}
從上述結(jié)果可以看出.需要轉(zhuǎn)義字符形成\\.才能對字符串分割。而且輸出結(jié)果也驗證了第一點regex后面的每個regex對應(yīng)字符串?dāng)?shù)組中的空字符串,末尾的部分舍棄。
將此字符串拆分為給定的regular expression(正則表達式)匹配
參數(shù):
regex–分割正則表達式;
limit–影響字符串?dāng)?shù)組的長度
limit > 0 : regex的匹配模式將最多被應(yīng)用limit - 1次,數(shù)組的長度不會超過limit,數(shù)組的最后一項有可能包含所有超出最后匹配的regex。
limit = 0 : 與不帶參數(shù)limit的split方法相同,結(jié)尾的空字符串被舍棄。
limit < 0 : 匹配模式將盡可能多的使用,而且字符串?dāng)?shù)組可以是任意長度。
結(jié)果:將字符串按分隔符分為字符串?dāng)?shù)組。
String str = "3..2.1.1....1.6...";
當(dāng)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));
}
}
}
當(dāng)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轉(zhuǎn)換為數(shù)組;
以上就是關(guān)于“Java字符串split方法介紹”,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下本站的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,細(xì)致全面,很適合0基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家能夠有所幫助。
初級 202925
初級 203221
初級 202629
初級 203743