3

我正在尝试从字符串中获取子字符串。我已经编写了逻辑来提供开始索引和结束索引,但低于异常。代码是:

final int startIndex = header.indexOf(startValue + ":")
                + (startValue + ":").length();
final int endIndex = header.indexOf(endValue + ":");
return header.substring(startIndex, endIndex).trim();

例外:

'字符串索引超出范围:-4' java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-4 在 java.lang.String.substring(String.java:1967)

任何帮助,将不胜感激。

4

2 回答 2

5

的相关代码substring为:

1965    int subLen = endIndex - beginIndex;
1966    if (subLen < 0) {
1967        throw new StringIndexOutOfBoundsException(subLen);
1968    }

如果您-4在异常消息中看到,这意味着endIndex - beginIndex == -4.

显然,endIndex应该大于或等于beginIndex,这样差异就不会是负数。

查看完整的方法(此版本的代码似乎与您的版本相匹配,基于行号 - 1967 - 其中引发了异常):

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > value.length) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    int subLen = endIndex - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return ((beginIndex == 0) && (endIndex == value.length)) ? this
            : new String(value, beginIndex, subLen);
}

您可以看到如果是,您会收到-1错误消息。beginIndex-1

但是如果beginIndex是非负数并且endIndex不是太大,那么您在异常消息中得到的数字是endIndex - beginIndex.

于 2021-03-08T09:59:38.510 回答
0

这不是一个确切的答案或更正,因为我认为您的方法需要改变。我建议使用基于正则表达式的方法来查找文本正文中的所有键值对。考虑这个版本:

String input = "<html> <head></head> <body> Sent: Thu Feb 04 19:06:38 IST 2021 From: test@test.com To: tester1@test.com,tester2@test.com Subject:";
String pattern = "\\b(\\S+): (.*?)(?= \\S+:)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);

while (m.find()) {
    System.out.println("Found: (" + m.group(1) + ", " + m.group(2) + ")");
}

这打印:

Found: (Sent, Thu Feb 04)
Found: (From, test@test.com)
Found: (To, tester1@test.com,tester2@test.com)

您可以遍历文本并搜索您需要的任何键/值。在这种情况下避免子字符串操作,因为它会留下太多边缘情况。

于 2021-03-08T10:09:59.213 回答