【问题标题】:Java finding substringJava 查找子字符串
【发布时间】:2011-01-18 15:15:11
【问题描述】:

我有以下字符串:

oauth_token=safcanhpyuqu96vfhn4w6p9x&**oauth_token_secret=hVhzHVVMHySB**&application_name=Application_Name&login_url=https%3A%2F%2Fapi-user.netflix.com%2Foauth%2Flogin%3Foauth_token%3Dsafcanhpyuqu96vfhn4w6p9x

我正在尝试解析 oauth_token_secret 的值。我需要从等号 (=) 到下一个 & 号 (&) 的所有内容。所以我需要解析出:hVhzHVVMHySB

目前,我有以下代码:

Const.OAUTH_TOKEN_SECRET = "oauth_token_secret";

Const.tokenSecret = 
  content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET + "="))
    + (Const.OAUTH_TOKEN_SECRET + "=").length(), 
      content.length());

这将从 oauth_token_string 的开头开始,但不会在下一个 & 符号处停止。我不确定如何指定在以下&符号的末尾停止。谁能帮帮我?

【问题讨论】:

    标签: java string substring


    【解决方案1】:

    indexOf() 方法允许您指定可选的fromIndex。这使您可以找到下一个 & 符号:

    int oauth = content.indexOf(Const.OAUTH_TOKEN_SECRET);
    if (oauth != -1) {
      int start = oath + Const.OATH_TOKEN_SECRET.length(); // or
      //int start = content.indexOf('=', oath) + 1;
      int end = content.indexOf('&', start);
      String tokenSecret = end == -1 ? content.substring(start) : content.substring(start, end);
    }
    

    【讨论】:

    • 成功了,感谢您向我展示了如何做到这一点!
    【解决方案2】:
    public static Map<String, String> buildQueryMap(String query)  
    {  
      String[] params = query.split("&");  
      Map<String, String> map = new HashMap<String, String>();  
      for (String param : params)  
      {
        String[] pair = param.split("=");
        String name = pair[0];  
        String value = pair[1];  
        map.put(name, value);  
      }  
      return map;  
    }
    
    // in your code
    Map<String, String> queryMap = buildQueryMap("a=1&b=2&c=3....");
    String tokenSecret = queryMap.get(Const.OAUTH_TOKEN_SECRET);
    

    【讨论】:

    • +1 这是最健壮的,尽管格式错误的输入字符串可能会给出空指针或数组索引异常。
    【解决方案3】:

    使用String.split 可以提供更简洁的解决方案。

    static String getValue(String key, String content) {
      String[] tokens = content.split("[=&]");
      for(int i = 0; i < tokens.length - 1; ++i) {
        if(tokens[i].equals(key)) {
          return tokens[i+1];
        }
      }
      return null;
    }
    

    点击here试驾! ;-)

    【讨论】:

      【解决方案4】:

      更好的解决方案是使用Pattern 和相应的Matcher 类。

      通过使用捕获组,您可以在一个步骤中检查并“删除”适当的子字符串。

      【讨论】:

        猜你喜欢
        • 2015-09-16
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        • 2013-10-22
        • 2017-05-15
        • 1970-01-01
        • 2012-01-25
        • 2014-02-04
        相关资源
        最近更新 更多