简体   繁体   中英

How to implement the template(replacing string with the element of list) in java.

I am developing an application in which I came across the requirement where I need to do the replacement of identifying words with the strings ie replacing the actual data in templates. In this I am getting the data from an arraylist and for that I have implemented the following solution.

List<String> abc = new ArrayList<String>();
        abc.add("willy brown");
        abc.add("jamster");
        String message="//$^$// has commented on //$^$// .";
        String messages[] = message.split(" ");
        StringBuffer finalMessage = new StringBuffer();
        for(int i=0,j=0; i<messages.length && j<=abc.size(); i++){
            System.out.println("messages : " + messages[i]);
            if(messages[i].equals("//$^$//")){
                messages[i] = abc.get(j);
                System.out.println("after changes " +messages[i]);
                j++;
            }
            finalMessage.append(messages[i] +" ");
        }
        System.out.println("final message: " + finalMessage);

I just want to know if there is any better way to implement this and also if there is any vulnerability in this.

I would use MessageFormat.format for this:

    List<String> abc = new ArrayList<String>();
    abc.add("willy brown");
    abc.add("jamster");

    String message = "{0} has commented on {1}";
    String finalMessage = MessageFormat.format(message, abc.toArray(new String[abc.size()]));
    System.out.println(finalMessage);

You can use the built in String and StringBuffer methods to perform this task without having to break apart the message into an array. I also suggest extracting your field identifier into a separate variable. God forbid you miss-type it somewhere!

    String fieldIdentifier = "//$^$//";

    List<String> abc = new ArrayList<>();
    abc.add("willy brown");
    abc.add("jamster");

    String message= fieldIdentifier + " has commented on "  + fieldIdentifier + ".";
    StringBuffer finalMessage = new StringBuffer(message);

    int fieldCount = 0;

    while(finalMessage.indexOf(fieldIdentifier) > -1) {
        int index = finalMessage.indexOf(fieldIdentifier);
        finalMessage = finalMessage.replace(index, index + fieldIdentifier.length(), abc.get(fieldCount));

        fieldCount++;
    }

    System.out.println("final message: " + finalMessage);

Edit: using StringBuffer for these kinds of operations is highly preferable, since it is mutable and much faster than using String.

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