如何用特定的单词替换单词

时间:2014-04-23 10:20:47

标签: java string

我有一个字符串:

String s="<p>Dear <span>{customerName}, your {accountName} is actived </span></p><p>&nbsp;</p><p><span>Congrats!.....</span></p>";

所以我想接受CustomerName和accountName字样并替换客户详细信息。任何人都可以告诉我如何更换。这里customerName和accountName是动态变化的。因为那些数据库中的列有时是不同的列。所以我想在{和}中找到单词并需要替换列数据。

5 个答案:

答案 0 :(得分:1)

使用以下代码

s = s.replace("{customerName}", realCustomerName);
s = s.replace("{accountName}", realAccountNAme);

使用String的replace函数,第一个参数是要替换的字符串,第二个参数是要插入的字符串。

答案 1 :(得分:0)

尝试:

s=s.replace('{customerName}',CustomerName ).replace('{accountName}',accountName);

其中CustomerNameaccountName将是保存客户详细信息的字符串

答案 2 :(得分:0)

如果您只想更换单词,可以执行以下操作:

String s="<p>Dear <span>{customerName}, your {accountName} is actived </span></p><p>&nbsp;</p><p><span>Congrats!.....</span></p>";
s.replace( "{customerName}", customer.getName() );
s.replace( "{accountName}", account.getName() );

或者,如果您自己构建字符串并且可以对其进行修改,那么最好执行以下操作:

String s="<p>Dear <span>%1$s, your %1$s is actived </span></p><p>&nbsp;</p><p><span>Congrats!.....</span></p>";
// You may also just create a new String object...
s = String.format( s, customer.getName(), account.getName() );

答案 3 :(得分:0)

最后,我找到了使用正则表达式替换单词的答案。这里的单词b / w~需要替换,这些单词不固定,动态地将从UI文本区域添加到字符串中。

import java.util.regex.Matcher; import java.util.regex.Pattern;

公共类RegularEx {

/**
 * @param args
 */

public static void main(String args[]) {
    Pattern pattern = Pattern.compile("\\~.*?\\~");
    StringBuilder s = new StringBuilder(
            "~ABCD~~BBCc~All the best ~ABCD~~BBCc~~in~~Raja~ Such kind of people ~in~~Raja~~ABCD~~BBCc~~in~~Raja~rajasekhar~ABCD~~BBCc~~in~~Raja~ Bayanapalli ~Chinthalacheruvu~");
    Matcher matcher = pattern.matcher(s);
    // using Matcher find(), group(), start() and end() methods
    String s1 =new String("~ABCD~~BBCc~All the best ~ABCD~~BBCc~~in~~Raja~ Such kind of people ~in~~Raja~~ABCD~~BBCc~~in~~Raja~rajasekhar~ABCD~~BBCc~~in~~Raja~ Bayanapalli ~Chinthalacheruvu~");
    int i = 0;
    while (matcher.find()) {
        String grp = matcher.group();
        int si = matcher.start();
        int ei = matcher.end();
        System.out.println("Found the text \"" + grp

        + "\" starting at " + si + " index and ending at index " + ei);
        s1=s1.replaceAll(grp, "Raja");
        //System.out.println("FinalString" + s1);
    }
    System.out.println("------------------------------------\nFinalString" + s1);

}

}

答案 4 :(得分:-1)

 s = s.replace("{customerName}", "John Doe");
 s = s.replace("{accountName}", "jdoe");