Java映射替换一个或多个映射

Java映射替换一个或多个映射,java,regex,replace,Java,Regex,Replace,例如,我有一个字符串“PARAMS@FOO@BAR@”和字符串数组{“一”、“二”、“三”} 如何将数组值一一映射到字符串(替换标记),以便最终得到:“PARAMS one,FOO two,BAR three” 谢谢你你可以这么做 String str = "PARAMS @ FOO @ BAR @"; String[] arr = {"one", "two", "three"}; for (String s : arr) str = str.replaceFirst("@", s)

例如,我有一个字符串
“PARAMS@FOO@BAR@”
和字符串数组
{“一”、“二”、“三”}

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

谢谢你

你可以这么做

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

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

在此之后,
str
将保持
“参数一个FOO两个BAR三个”
。当然,要包含逗号,您可以用“
s+”替换“

也可以这样做:-

    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());
String str=“PARAMS@FOO@BAR@”;
字符串[]数组=新字符串[]{“一”、“二”、“三”};
String[]original=str.split(“@”);
StringBuilder=新的StringBuilder();
for(int i=0;i
注意-类字符串中非常有用的方法:。它有助于简洁地解决您的问题:

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"