2012-10-28 67 views
3

例如,我有一個字符串"PARAMS @ FOO @ BAR @"和字符串數組{"one", "two", "three"}Java地圖替換one-ot-one

你將如何映射數組值到字符串(替換標記)一對一,以便最終我會得到:"PARAMS one, FOO two, BAR three"

謝謝

回答

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

你也可以這樣來做: -

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()); 
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"