Java 子串问题

Java 子串问题,java,substring,charat,Java,Substring,Charat,我试图分解一个字符串192.168.1.2:6060;rport;branch=z9hG4bKNskFdtGO4“ 我想在第一个分号之前提取端口:ip,在等号之后提取分支编号 我试过的代码是 temp = in.next(); System.out.println(temp.contains(";")); System.out.println(temp.contains("=")); System.out.println("Temp: " + temp + " "); sipName = tem

我试图分解一个字符串
192.168.1.2:6060;rport;branch=z9hG4bKNskFdtGO4“

我想在第一个分号之前提取
端口:ip
,在等号之后提取分支编号

我试过的代码是

temp = in.next();
System.out.println(temp.contains(";"));
System.out.println(temp.contains("="));
System.out.println("Temp: " + temp + " ");
sipName = temp.substring(0, temp.charAt(';'));
branch = temp.substring(temp.charAt('='));
我添加了println以显示是否至少在字符串中找到了这些字符

当我运行代码时,在第
sipName=temp.substring(0,temp.charAt(“;”);

我的控制台输出是:

true
true
Temp: 192.168.1.2:6060;rport;branch=z9hG4bKb8NGxwdoR
Exception in thread "Thread-1" java.lang.StringIndexOutOfBoundsException: String index out of range: 59
...
即使我只是尝试
System.out.println(temp.charAt(“;”);

我不知道为什么会这样。有人能解释吗?我很困惑。

调用
temp.indexOf(';')
而不是
temp.charAt(';')
。同样,调用
temp.indexOf('=')
而不是
temp.charAt('=')

indexOf
告诉您给定字符第一次出现在字符串中的位置。
charAt
返回字符代码,而不是字符串中的位置,因此在哪里使用它没有意义


(无论如何,当你调用
charAt
时,你传递的是字符串中的一个位置,而不是字符代码。你几乎可以把它看作是
索引of
的对立面)

字符串。charAt
接受一个int。你传递的是字符。 请参阅此处以供参考:
用indexOf替换chatAt

这个字符是一个逻辑错误,你实际上想要indexOf

好的,其他人更快;)

你需要的是

temp.indexOf(";");
编译时不会出现任何异常,因为它会转换“;“转换为其ASCII值59。因此它尝试访问此字符串的第60个元素。最后,这将为您提供一个

StringIndexOutOfBoundsException

运行时。

感谢您的快速回答,我已经有一段时间没有使用子字符串了。现在感觉有点傻。我会在计时器冷却后接受答案。
StringIndexOutOfBoundsException