简体   繁体   中英

How can I substitute an arbitrary number of substrings?

I'm working on a basic RPC design. From a listener, I retrieve a desired RPC like:

ArrayList<String> params = new ArrayList<String>();
params.add(Node.getLocal().getHostname());
params.add("test");
RPC rawRPC = StorageControl.getRPC(StorageControl.RPC_HelloMaster, params));

My StorageControl class is pretty simple right now,

public class StorageControl {
    public StorageControl(){
        availableRPCs.put(RPC_HelloMaster, new RPC("[%s] Hello, Master. [%s]"));
    }

    public static final String RPC_HelloMaster = "helloMaster";

    private static String MasterHostname;
    public static String getMaster(){ return MasterHostname; }
    public static void setMaster(String host){ MasterHostname = host; }

    private static Map<String, RPC> availableRPCs = new HashMap<String, RPC>();
    public static RPC getRPC(String key, ArrayList<String> params) {
        RPC rawRPC = availableRPCs.get(key);

        // This is what fails
        for (String param : params){
            rawRPC.msg = String.format(rawRPC.msg, param);
        }

        return rawRPC;
    }
}

RPC is just a simple class, containing a single variable, msg

So, the idea is that I want to retrieve RPCs, that may have a variable number of variables that need substituted. Is there a more elegant way (that actually works) to do this? What I have now fails with a MissingFormatArgumentException , I assume because the first loop doesn't attempt to replace beyond the 1st variable.

At first we need to know how format works,

String x = String.format("%s %s","hello","world");

then x will have "hello world". But if we do this

String x = String.format("%s %s","hello"); 

It will give you a illegal argument exception because there are not enough arguments to replace.

So you need to pass all arguments at once. Now variable arguments actually array of args. So you can do this.

String stringToFormat = "%s %s %s";
String[] ags = {"hello","world","gg"};
stringToFormat = String.format(stringToFormat,ags);
System.out.println(stringToFormat);

In your case, you can just do this without loop

rawRPC.msg = String.format(rawRPC.msg, params.toArray(new String[params.size()]));

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