例如,我有一个 String"PARAMS @ FOO @ BAR @"
和 String 数组{"one", "two", "three"}
。
您将如何将数组值一对一映射到字符串(替换标记),这样最后我会得到:"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
将举行"PARAMS one FOO two BAR three"
。当然,要包含逗号,您可以替换为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: 中非常有用的方法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"