Reputation: 155
I wanted to get the value from the last part of a String, here's my example String
String str="www.mywebsite.com?id=0001&user=myname"
I like to get the word myname from that String, All examples that I'm seeing is like this
String getUser = str.substring(str.length() - 6);
but user value length changes every transaction so I can't fix that to any value. Can anyone please help me in how I will be able to get the user value from that String. Thanks.
Upvotes: 3
Views: 1163
Reputation: 1
String str="www.mywebsite.com?id=0001&user=myname";
String user = getQueryParamValue(str);
public static final String getQueryParam(String url) {
List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");
for (NameValuePair param : params){
if("user".equalsIgnoreCase(param.getName())) {
return param.getValue();
}
}
return null;
}
Upvotes: 0
Reputation: 21
If your string is going to be a uri, you can use Uri's getQueryParameter:
String str="www.mywebsite.com?id=0001&user=myname";
Uri uri = Uri.parse(str);
return uri.getQueryParameter("user");
Upvotes: 2
Reputation: 876
Try this
String foo = "www.mywebsite.com?id=0001&user=myname";
String[] split = foo.split("=");
String name = split[split.length-1];
with String.split(), you can split strings with a delimiter and put the values in an array. It is similar to PHPs' explode method.
Upvotes: 0
Reputation: 539
String getUser=str.subString(str.lastIndexOf("=")+1,Str.length());
Will return myname.
Upvotes: 5
Reputation: 2436
Try this
String getUser = str.substring(str.lastIndexOf("=") + 1);
Upvotes: 0