-1

我确实拆分为字符串,但我没有考虑异常。所以错误就出来了。例如,如果字符串是“2012-10-21,20:00:00,”

Here is the codes:
String str = "2012-10-21,20:00:00,,";
String a[] = str.split(",");
String timestamp = a[0] + "T" + a[1];
String temp = a[2];


System.out.println(timestamp);
System.out.println(temp);

这是错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

实际上,a[2] 为空,但我不知道如何处理这个问题。因为在我的字符串数组中,一些重新编码包含了 temp 的值,例如“2012-10-21,20:00:00,90”。

谢谢你。

4

2 回答 2

7

split 确实删除了空元素。您需要使用两个参数版本:

str.split(",",-1);

请参见此处: Java String split 删除了空值

于 2013-08-26T15:01:55.480 回答
0

您的问题出在这行代码中

String temp = a[2];

看来您只有 2 个元素,并且 a[2] 引用了数组中的第三个元素,因为索引从 0 开始,而不是 1。您的第 3 个元素实际上已被删除,因为它是空的。

如果您想获取数组的大小以防止自己超出范围,可以在数组上调用 sizeof 函数。

int main(){

      int myarray[3]; //an array of 3 intigers for example

      cout << sizeof(myarray); //print the array size in bytes
]

其输出将是“12”

输出是 12,因为 sizeof 将返回数组的大小,而不是元素的数量,所以 int 对于 int 的情况,即 4 个字节,你得到 12。

于 2013-08-26T15:02:38.230 回答