繁体   English   中英

拆分字符串后,ArrayOutOfBoundsException

[英]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

的java.net.URL

这还具有使用不仅是主机名的URL的好处,例如,给定http://www.example.co.aq/query.exe?field=name&id=12#fragment ,这将输出Top-level aq

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM