surya surya - 3 months ago 32
Java Question

String Formatting in java to replace the array index with the pointed string element

We have to replace as follows Alibaba site china comparison best-Replacement array
{} is {4} online {3} shopping {} in {}-positional argument array

Output must be Alibaba is best online comparison shopping site in China.Please help me in getting so

Answer

You can use MessageFormat like this

public static void main(String args[]) throws Exception{
    String result = MessageFormat.format("{0} is {4} online {3} shopping {1} in {2}" ,
            "Alibaba" ,"site",  "china", "comparison", "best");
    System.out.println(result);
}

it will output

Alibaba is best online comparison shopping site in china