【问题标题】:Substring of a string java字符串 java 的子字符串
【发布时间】:2016-03-10 01:29:17
【问题描述】:

下面是一个字符串,我想从中获取粗体 id。

String s = "> Index1 is: 261 String is: href: <a href="https://www.clover.com/v3/merchants/4B8BF3Y5NJH7P/orders/K0AH5696MRG6J?access_token=4ffcfacefd3b2e9611a448da68fff91f">https://www.clover.com/v3/merchants/4B8BF3Y5NJH7P/orders/K0AH5696MRG6J?access_token=4ffcfacefd3b2e9611a448da68fff91f</a>, id: **K0AH5696MRG6J**, currency: USD, title: Greta , note:  This is test ,";
int ind = s.indexOf("id:");
s = s.substring(ind,s.indexOf(","));

它给出了一个超出范围的错误索引。

我知道有错误是因为 substring(int,int) 中的第二个参数值不正确。

我正在尝试获取id:, 之间的子字符串。

任何帮助

【问题讨论】:

    标签: java string substring


    【解决方案1】:

    你得到一个IndexOutOfBoundsException,因为substring found that end index was less than the begin index

    抛出: IndexOutOfBoundsException - 如果 beginIndex 为负数,或者 endIndex 大于此 String 对象的长度,或者 beginIndex 大于 endIndex。

    您最初的indexOf 调用正确地找到了id:,但是对s.indexOf(",") 的调用找到了字符串中的第一个,,它恰好在id: 之前。

    使用overload of indexOf that takes a second argument - 开始查找的索引。

    s = s.substring(ind,s.indexOf(",", ind));
    

    【讨论】:

      【解决方案2】:

      我建议你使用

      s.indexOf(",", ind)
      

      获取id: 之后的逗号,而不是字符串中的第一个逗号。

      如果您还没有阅读 String 中的所有方法,我建议您这样做,因为您将一次又一次地使用这个类。

      【讨论】:

      • @user1486269 在阅读java.langjava.util 的Javadocs 并希望我能早点完成之前,我不知道自己使用Java 多少年了。
      【解决方案3】:

      你的 "," 索引在你的 "id:" 索引之前。您必须在 id 之后进行搜索

      // Search id:
      int ind = s.indexOf("id:");
      
      // After that: search comma
      int comma = s.indexOf(",", ind +1);
      

      这解释了这类问题:

      How to use substring and indexOf for a String with repeating characters?

      【讨论】:

      • ID如何搜索?
      猜你喜欢
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      相关资源
      最近更新 更多