简体   繁体   中英

JAVA: format strings with a counter

I want to build a url based on the template that was previously defined:

public class Main {
public static void main(String[] args) {
    String unformattedUrl = "http://myweb.com?param[%1$d]=[%2$s]&param[%1$d]=[%3$s]&param[%1$d]=[%4$s]";
    System.out.println(String.format(unformattedUrl, 1, "first", "second", "third"));
}

}

I want to get the next string after formatting:

http://myweb.com?param[1]=[first]&param[2]=[second]&param[3]=[third]

The problem is that I get parameters in Runtime and their number is not known in advance.

I can pass an array of parameters to String.format(...) function, but I don't know how to add a counter.

Is it possible to make it without loops, manual replaces or concatenations?

Don't try to do this directly with a String.format : loop over the parameters, and append them to a StringBuilder :

StringBuilder sb = new StringBuilder("http://myweb.com?");
for (int i = 0; i < params.length; ++i) {
  if (i != 0) sb.append("&");
  sb.append("param");
  sb.append(i + 1);
  sb.append("=");
  sb.append(escape(params[i]));
}
String url = sb.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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