【发布时间】:2014-04-22 22:15:16
【问题描述】:
在类的某个地方我声明了一个临时字符串变量:
String name;
我将使用它来存储来自文本的数据。文本有许多具有这两种格式的字段:
Type: text/html
name=foo
对于这种情况,我对类型name=foo
所以,我之前使用split打破了文本行
String lines[] = text.split("\n");
再一次,我将使用split 来识别所提到类型的字段。在下面的代码中,while 循环在检测到 name=foo 字段时停止,并在控制台中打印该字段的值。
int i = 0; // Counter for the while cycle
while (!(lines[i].split("=")[0].equals("name"))) {
i++;
if (lines[i].split("=")[0].equals("name")) // If the field is name...
System.out.println(lines[i].split("=")[1]); // Prints the value of the field
name = lines[i].split("=")[1]; // <-- My problem is here
}
当我想将字段的值复制到前面提到的 String 变量时,我的问题就开始了,这给了我一个 java.lang.ArrayIndexOutOfBoundsException。
我需要该字符串稍后对其进行处理。 安全地将该字段的值复制到字符串变量的任何想法?
【问题讨论】:
-
您确定您的所有行[] 都包含“xxxx=xxxxxx”类型的数据吗?
-
你应该显示“name”的类类型。
-
@SaraSeppola 文本可能包含“XXX:XXX”和“XXX=XXX”两种类型的数据。
-
那么,如果它有一个
:而不是=,则生成的数组没有1索引......你会收到你显示的(正确的)错误.