【发布时间】:2012-04-17 01:57:11
【问题描述】:
我正在尝试从字符串中删除最后一个字符,如果它是/。我正在使用字符串数组temp[] 来存储字符串。
这是我的代码:
char ch = ' ';
for (int st = 0; st < temp.length; st++)
{
ch = temp[st].charAt(temp[st].length()-1);
if (ch == '/')
temp[st] = temp[st].substring(0, temp[st].length()-1);
result2.append(temp[st]);
}
但我得到了
StringIndexOutOfBoundsException -1
我做错了什么?
【问题讨论】:
-
你忘记了防御性编程的一个关键规则——永远不要相信输入。您假设所有字符串都不为空。
-
为什么要将字符串存储在 char[] 中?
-
临时有什么东西吗?因为当 temp 为空时,您会得到一个 null 或 length-1 可能超出范围。但是使用 if (str.endsWith("/")) 然后删除最后一个字符。