gpt4 book ai didi

java - 分割字符串后,ArrayOutOfBoundsException

转载 作者:太空宇宙 更新时间:2023-11-04 06:37:10 27 4
gpt4 key购买 nike

假设 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] 显然超出范围。

关于java - 分割字符串后,ArrayOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231639/

27 4 0
文章推荐: c 字符串数组中的指针
文章推荐: python - 最简单的 django 定时/计划任务(例如 : reminders)?
文章推荐: c - c中的字符串函数
文章推荐: java - Arraylist 到 Object[][]