3

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

您将如何将数组值一对一映射到字符串(替换标记),这样最后我会得到:"PARAMS one, FOO two, BAR three".

谢谢

4

3 回答 3

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 + ",".

于 2012-10-28T21:04:35.937 回答
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());
于 2012-10-28T21:07:54.657 回答
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"
于 2012-10-29T12:08:07.883 回答