Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java finding substring

I have the following String:

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

I am trying to parse out the value for oauth_token_secret. I need everything from the equals sign (=) to the next ampersand sign (&). So I need to parse out: hVhzHVVMHySB

Currently, I have the following code:

Const.OAUTH_TOKEN_SECRET = "oauth_token_secret";

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

This will start at the beginning of the oauth_token_string, but it will not stop at the next ampersand. I am unsure how to specify to stop at the end of the following ampersand. Can anyone help me?

like image 707
littleK Avatar asked Sep 28 '26 23:09

littleK


2 Answers

The indexOf() methods allow you to specify an optional fromIndex. This allows you to find the next ampersand:

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);
}
like image 149
cletus Avatar answered Sep 30 '26 13:09

cletus


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);
like image 21
marklai Avatar answered Sep 30 '26 11:09

marklai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!