简体   繁体   English

Android java 通过特殊字符拆分字符串失败

[英]Android java split string via special character fails

I would like to attach a platform parameter to a url with ?我想将平台参数附加到 url 与? if the url has no query string and using & if url has a query string如果 url 没有查询字符串并且使用&如果 url 有查询字符串

SO i have added the following所以我添加了以下内容

 String api_url;
 //costructor next to assign apiurl value

 //method to extract url and process request
 processData(){
    String apiUrl = "";
    String[] urlParams = this.api_url.split("\\?");
    if (urlParams.length > 0){
        apiUrl = this.api_url+"&platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
    }else {
        apiUrl = this.api_url+"?platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
    }
}

The above always evaluates the urlParams to a an array even when a url doesnt contain the ?即使urlParams不包含?

Example for a url url 示例

http://test.com

is resolved with the above code as用上面的代码解决为

http://test.com&platform=12

But i expected it to be as http://test.com?platform=12但我希望它是http://test.com?platform=12

I have tried adding我试过添加

String[] urlParams = this.api_url.split("?"); 

But it throws an error of Dangling metacharacter .但它会抛出Dangling metacharacter的错误。 What am i missing out on this.我错过了什么。 Why does this fail.为什么会失败。

This is expected behaviour for String#split .这是String#split的预期行为。 Running "http://test.com".split("\\?") returns an array with one element, "http://test.com" .运行"http://test.com".split("\\?")返回一个包含一个元素"http://test.com"的数组。 So, just update your condition to if(uriParams.length > 1) .因此,只需将您的条件更新为if(uriParams.length > 1)

You could also consider parsing your String to a Uri, as you may not need this check and could possibly instead use:您还可以考虑将您的 String 解析为 Uri,因为您可能不需要此检查,而可以使用:

Uri.parse(api_url)
    .buildUpon()
    .appendQuery("platform", tokenService.getToken(AppSettingsKeys.PLATFORM))
    .build().toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM