[英]After splitting a string, ArrayOutOfBoundsException
假設url = "http://gmail.com"
。
我嘗試從中創建一個字符串dnsname = "Top-level com"
。
現在,我們運行以下代碼:
System.out.println(url);
String[] urlsplit = new String[3];
System.out.println(url.substring(10,11));
urlsplit = url.split(url.substring(10,11));
String dnsname = "Top-level " + urlsplit[urlsplit.length - 1];
System.out.println(dnsname);
作為輸出,我們得到:
http://www.gmail.com
.
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
我看不到我犯的錯誤,但是肯定有一個錯誤。
我認為該點被視為表示“任何字符”的正則表達式模式,因此您的split方法將返回一個空數組。 只需執行以下操作:
String url = "http://gmail.com";
System.out.println(url);
//Escape the . to tell the parser it is the '.' char and not the regex symbol .
String[] urlsplit = url.split("\\.");
String dnsname = "Top-level " + urlsplit[urlsplit.length - 1];
System.out.println(dnsname);
如果使用“。”運行相同的代碼。 代替 ”\\。” 您將遇到與代碼中相同的問題。 因為s.split(“。”)實際上返回一個空數組,所以urlsplit.length - 1
為負,而urlsplit[urlsplit.length - 1]
顯然超出范圍。
這是避免記住所有正則表達式元字符的最佳方法:
String url = "http://gmail.com";
System.out.println(url);
String[] urlsplit = new String[3];
System.out.println(url.substring(12, 13));
urlsplit = url.split(Pattern.quote(url.substring(12, 13)));
String dnsname = "Top-level " + urlsplit[urlsplit.length - 1];
System.out.println(dnsname);
注意:您可能會更好:
urlsplit = url.split(Pattern.quote("."));
如果運行此代碼,您將獲得:
http://gmail.com
.
Top-level com
問題是String#split接收到正則表達式,點(。)符號在正則表達式中是一個特殊字符,因此您需要將其作為普通符號發送。
更換
urlsplit = url.split(url.substring(10,11));
同
urlsplit = url.split("\\"+url.substring(10,11));
或者只是這樣做
urlsplit = url.split("\\.");
但是問題是為什么ArrayOutOfBoundsException
?
由於您的split
函數中的模式錯誤,因此永遠不會填充該數組。 並且您嘗試訪問它的第二個索引的值,因此在這種情況下,它給了您ArrayOutOfBoundsException
如果我正確理解您的問題,則需要輸出
Top-level com
如果這是您想要的URL,請考慮將java.net.URL
類與split()
一起使用。
import java.net.MalformedURLException;
import java.net.URL;
public class Program {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://gmail.com/");
System.out.println(url);
String[] hostParts = url.getHost().split("\\.");
String dnsname = "Top-level " + hostParts[hostParts.length - 1];
System.out.println(dnsname);
}
}
輸出:
http://gmail.com
Top-level gmail.com
這還具有使用不僅是主機名的URL的好處,例如,給定http://www.example.co.aq/query.exe?field=name&id=12#fragment
,這將輸出Top-level aq
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.