1. 程式人生 > 遊戲 >《真女神轉生5》惡魔介紹:武器發明者蚩尤

《真女神轉生5》惡魔介紹:武器發明者蚩尤

方法一:通過split()

此方法返回的是一個字串陣列型別。

1.只傳一個引數:split(String regex)

將正則傳入split(),根據給定正則表示式的匹配拆分此字串。不過通過這種方式擷取會有很大的效能損耗,因為分析正則非常耗時。

public class day1011 {
public static void main(String[]args){
String str="[email protected]";
String[] str1=str.split("y");
for(int i=0;i<str1.length;i++){
System.out.println(str1[i].toString());
}
}
}

執行結果:

hs

bc

usdg

[email protected]

2.傳入兩個引數:split(String regex,int limit)

regex -- 正則表示式分隔符。

limit -- 分割的份數。

將正則和份數傳入split()。根據給定正則表示式的匹配和想要分割的份數來拆分此字串。

public class day1011 {
public static void main(String[]args){
String str="hsybcyusdgyg@163@com";
String[] str1=str.split("@",2);
for(int i=0;i<str1.length;i++){
System.out.println(str1[i].toString());
}
}
}

執行結果:

hsybcyusdgyg

163@com

方法二:通過subString()方法來進行字串擷取

1、只傳一個引數:subString(int beginIndex)

將字串從索引號為beginIndex開始擷取,一直到字串末尾。(注意索引值從0開始);

public class day1011 {
public static void main(String[]args){
String str="hsybcyusdgyg@163@com";
String st2=str.substring(5);
System.out.println(st2);
}
}

執行結果:

yusdgyg@163@com

2、傳入兩個引數:substring(int beginIndex, int endIndex)

從索引號beginIndex開始到索引號endIndex結束(返回結果包含索引為beginIndex的字元不包含索引endIndex的字元),如下所示:

public class day1011 {
public static void main(String[]args){
String str="hsybcyusdgyg@163@com";
String st2=str.substring(2,7);
System.out.println(st2);
}

執行結果:

ybcyu

3、根據某個字元擷取字串

這裡根據”@”擷取字串(也可以是其他子字串)

public class day1011 {
public static void main(String[]args){
String str="hsybcyusdgyg@163@com";
String st2=str.substring(2,str.indexOf("@"));
System.out.println(st2);
}
}

執行結果:

ybcyusdgyg

歡迎大家批評指正,指出問題,謝謝!