假设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


我看不到我犯的错误,但是肯定有一个错误。

最佳答案

我认为该点被视为regex模式,表示“任何字符”,因此您的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]显然超出范围。

10-05 23:03