【问题标题】:Java: Index of whitespace problemsJava:空白问题索引
【发布时间】:2013-11-12 10:36:23
【问题描述】:

我的代码有问题,我想知道是否有人可以帮助我。

//I'm looking from "?PARAMETER" in a text.
locatie = inhoud.indexOf("?");
inhoud = inhoud.substring(locatie);
lengte = inhoud.length();

//is this usefull to do?
inhoud = inhoud.trim();

//make string from question mark to next space
spatie = inhoud.indexOf(" ");
parameter = inhoud.substring(++locatie, spatie); //this line throws an error
System.out.println(parameter);

此代码返回:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: -2
        at java.lang.String.substring(String.java:1911)
        at MailMatcher.personaliseren(MailMatcher.java:51)
        at MailMatcher.menu(MailMatcher.java:28)
        at MailMatcher.main(MailMatcher.java:61)

这是我现在使用的输入:

text ?NAAM \n more text ?DAG some more

我现在希望对我的代码做的只是在控制台中回显参数。我这样做是为了学校;所以我只要求澄清错误 - 我会尝试自己找到解决方案。

【问题讨论】:

  • 哪一行会导致这个异常?
  • 参数 = inhoud.substring(++locatie, spatie);
  • ++locatie 在这种情况下没有意义,因为locatie 是原始字符串的索引,而不是子字符串。

标签: java whitespace indexof


【解决方案1】:

您的基本问题是因为您在这里找到的第一个索引:

locatie = inhoud.indexOf("?");

然后您创建一个子字符串并在此处再次使用相同的索引而不更改它(除了递增,我猜它是为了排除问号):

parameter = inhoud.substring(++locatie, spatie);

对于您帖子中的输入字符串,您最终得到的是:

parameter = inhoud.substring(6, 5);

我认为异常 (-2) 表示结束索引(4,因为结束索引是独占的)比开始索引小 2。

我想你想要的要么是

parameter = inhoud.substring(0, spatie);

parameter = inhoud.substring(1, spatie);

取决于您是否要排除问号。

修剪还会删除尾随和前导空格。如果这是您需要做的事情,它会很有用。在这种情况下,我会说它可能没用。您已经基于非空白字符创建了第一个子字符串,因此您可以确定没有前导空白。对于第二个子字符串,结束索引是独占的,因此如果您在空格上设置子字符串,您还可以确保没有尾随空格。

【讨论】:

  • 确实,非常感谢。我忘记了我的字符串以“?”开头现在是因为我以前把所有东西都扔掉了。
猜你喜欢
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2011-07-20
  • 1970-01-01
相关资源
最近更新 更多