Java映射替换一个或一个

时间:2012-10-28 21:02:12

标签: java regex replace

例如,我有一个String "PARAMS @ FOO @ BAR @"和一个String数组{"one", "two", "three"}

如何将数组值一对一映射到字符串(替换标记),以便最终得到:"PARAMS one, FOO two, BAR three"

谢谢

3 个答案:

答案 0 :(得分:3)

你可以做到

String str =  "PARAMS @ FOO @ BAR @";
String[] arr = {"one", "two", "three"};

for (String s : arr)
    str = str.replaceFirst("@", s);

在此之后,str将保留"PARAMS one FOO two BAR three"。当然,要包含逗号,您只需将其替换为s + ","

答案 1 :(得分:1)

您也可以这样做: -

    String str = "PARAMS @ FOO @ BAR @";
    String[] array = new String[]{"one", "two", "three"};
    String[] original = str.split("@");

    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < array.length; i++) {
        builder.append(original[i]).append(array[i]);
    }
    System.out.println(builder.toString());

答案 2 :(得分:1)

注意 - 类String中非常有用的方法:String.format。它有助于非常简洁地解决您的问题:

String str = "PARAMS @ FOO @ BAR @";
String repl = str.replaceAll( "@", "%s" ); // "PARAMS %s FOO %s BAR %s"
String result = String.format( repl, new Object[]{ "one", "two", "three" }); 
// result is "PARAMS one FOO two BAR three"