子串问题

时间:2013-11-27 23:59:59

标签: java substring charat

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

我想在第一个分号前提取port: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('='));

我添加了printlns以显示它们是否至少在字符串中找到了。

当我运行代码时,我在第sipName = temp.substring(0, temp.charAt(';'));行得到一个StringIndexOutOfBoundsError

我的控制台输出是:

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(';'));

,它也会失败

我不确定为什么会这样。有人能解释一下吗?我很难过。

5 个答案:

答案 0 :(得分:3)

致电temp.indexOf(';')而非temp.charAt(';')。同样,请拨打temp.indexOf('=')而不是temp.charAt('=')

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

(无论如何,当你拨打charAt时,你传递的是字符串中的位置,而不是字符代码。你几乎可以认为它与indexOf相反。)

答案 1 :(得分:1)

String.charAt接受一个int。你传了一个炭。 请参考此处以供参考: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29

答案 2 :(得分:1)

将chatAt替换为indexOf。

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

好的,其他人更快;)

答案 3 :(得分:1)

String sipName = StringUtils.substringBefore(str, ";");
String branch = StringUtils.substringAfter(str, "=");

StringUtils docs

答案 4 :(得分:1)

您需要的是

temp.indexOf(";");

你在编译时没有得到任何异常,因为它转换了“;”到它的ASCII值为59.所以它试图访问该字符串的第60个元素。最后,这给你一个

StringIndexOutOfBoundsException

在运行时。