2017-09-22 638 views
2

我正在使用一個代碼,我想用另一個字符串填充幾個字符串佔位符。這是我用來測試我的代碼的示例文本。Java:如何用Map <String,String>填充文本中的佔位符?

String myStr = "Media file %s of size %s has been approved" 

這是我如何填補佔位符。因爲我期望使用幾個地方持有人我已經使用java地圖<>。

Map<String, String> propMap = new HashMap<String,String>(); 
propMap.put("file name","20mb"); 
String newNotification = createNotification(propMap); 

我用下面的方法創建字符串。

public String createNotification(Map<String, String> properties){ 
    String message = ""; 
    message = String.format(myStr, properties); 

    return message; 
} 

如何用「文件名」和「20mb」替換兩個'%s'?

回答

0

嘗試幾種方法後,終於找到了一個好解。佔位符必須是這個[佔位符]。

public String createNotification(){ 
    Pattern pattern = Pattern.compile("\\[(.+?)\\]"); 
    Matcher matcher = pattern.matcher(textTemplate); 
    HashMap<String,String> replacementValues = new HashMap<String,String>(); 
    StringBuilder builder = new StringBuilder(); 
    int i = 0; 
    while (matcher.find()) { 
     String replacement = replacementValues.get(matcher.group(1)); 
     builder.append(textTemplate.substring(i, matcher.start())); 
     if (replacement == null){ builder.append(matcher.group(0)); }  
     else { builder.append(replacement); }  
     i = matcher.end(); 
    } 
    builder.append(textTemplate.substring(i, textTemplate.length())); 
    return builder.toString() 
} 
2

您對String#format的處理方法有誤。

它預計可變數量的對象將佔位符替換爲第二個參數,而不是地圖。要將它們組合在一起,您可以使用數組或列表。

String format = "Media file %s of size %s has been approved"; 

Object[] args = {"file name", "20mb"}; 
String newNotification = String.format(format, args); 
3

這不是地圖的目的。 你添加的是一個條目"file name" -> "20 mb",這基本上意味着屬性「文件名」的值爲「20 MB」。你想要做的是「維護一個元組的元組」。

請注意,格式化字符串具有固定數量的佔位符;你想要一個包含完全相同數量項目的數據結構;所以基本上是一個數組或List

因此,你想擁有的是

public String createNotification(String[] properties) { 
    assert(properties.length == 2); // you might want to really check this, you will run into problems if it's false 
    return String.format("file %s has size %s", properties); 
} 

如果你想創建一個地圖的所有項目的通知,你需要做的是這樣的:

Map<String,String> yourMap = //... 
for (Entry<String,String> e : yourMap) { 
    System.out.println(createNotification(e.getKey(), e.getValue())); 
} 
0

我覺得%s是Python的語法放置者,不能在Java環境中使用這個;而你的方法createNotification()定義需要兩個參數,不能只給一個參數。

+0

%S _can_在Java中使用:https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax –

1

可以使用VAR-ARGS簡單的做到這些格式:

String myStr = "Media file %s of size %s has been approved"; 

    String newNotification = createNotification(myStr, "file name", "20mb"); 

    System.out.println(newNotification); 

通行證變種-ARGS在createNotification方法,這裏是代碼:

public static String createNotification(String myStr, String... strings){ 
    String message = ""; 
    message=String.format(myStr, strings[0], strings[1]); 

    return message; 
} 
+0

但在每種情況下有不同數量的字符串被替換。所以我不認爲這可以使用。 – sndu

+0

@Sandu_prass這是針對給定字符串「媒體文件%s的大小爲%s已被批准」,我們可以通過進行一些更改使其變爲動態。 –

相關問題