用String的动态值替换字符串中的动态标签数量 - Java

时间:2014-04-19 18:31:23

标签: java replace

我在Java中有两个String。

**String str1 = "Dear Candidate **<Name>**, Your installment of home loan of a/c **<Loan A/c No.>** is due for Amount of Rs. **<Installment Amount>**. Please paid this installment before this due date **<Due Date>**.";

String str2 = "<Name>Deepraj <Loan A/c No.>301201 <Installment Amount>25000 <Due Date>20-Arpil-2014";**

我想用String str2&#34; Deepraj&#34; ...等信息替换所有String str1尖括号数据,如&#34;&#34;

"<Name>" replaced with "Deepraj"
"<Loan A/c No.>" replaced with "301201"
"<Installment Amount>" replaced with "25000"
"<Due Date>" replaced with "20-April-2014"

如果有任意数量的尖括号,str1或str2中的数据可以动态替换。

请任何人帮助我以动态或静态形式输出。

由于

1 个答案:

答案 0 :(得分:0)

上述问题的解答:

public static String replaceTagData() {
    String str = "Dear Candidate **<Name>**, Your installment of home loan of a/c **<Loan A/c No.>** is due for Amount of Rs. **<Installment Amount>**. Please paid this installment before this due date **<Due Date>**.";

    if(str.length() > 1) {
        
        Map<String, String> map = new HashMap<>();
        map.put("Name", "Test");
        map.put("Loan_Acc", "0987654321");
        map.put("Installment_Amount", "25000");
        map.put("Due_Date", "12-03-2021");

        if(map != null && map.size()>0) {
            str = str.replace("<Name>", map.get("Name")).replace("<Loan A/c No.>", map.get("Loan_Acc")).replace("<Installment Amount>", map.get("Installment_Amount")).replace("<Due Date>", map.get("Due_Date"));
            System.out.println(str);
        }
    }
    return str;
}