【问题标题】:Replace instances of character in a string with array values用数组值替换字符串中的字符实例
【发布时间】:2013-06-03 06:42:07
【问题描述】:

我将如何用数组中的值替换字符串中的字符或字符串的所有实例?

例如

String testString = "The ? ? was ? his ?";

String[] values = new String[]{"brown", "dog", "eating", "food"};

String needle = "?";

String result = replaceNeedlesWithValues(testString,needle,values);

//result = "The brown dog was eating his food";

方法签名

public String replaceNeedlesWithValues(String subject, String needle, String[] values){
    //code
    return result;
}

【问题讨论】:

  • 这是家庭作业吗?
  • //code (..for you to attempt)
  • 不。不是作业。我可以尝试编写一些使用大量子字符串的东西,但我知道有一种更有效的方法可以做到这一点。

标签: java arrays string


【解决方案1】:

通过使用String.format

public static String replaceNeedlesWithValues(String subject, String needle, String[] values) {
    return String.format(subject.replace("%", "%%")
                                .replace(needle, "%s"),
                         values);
}

:-)

当然,您可能只想直接使用String.format

String.format("The %s %s was %s his %s", "brown", "dog", "eating", "food");
// => "The brown dog was eating his food"

【讨论】:

  • 这很聪明...我喜欢这个。
  • 完美。谢谢。我知道有比找到针的位置然后使用子字符串更好的方法。
  • @David 当然,但这也说明在代码中直接使用String.format 会更好(使用%s 作为占位符而不是?)。 :-)
  • 您可以编辑您的答案以显示这一点吗?我之前没有使用过 replace() 或 format()
  • @David 当然。 (replace 只是将您的? 替换为%s;一般用法不需要​​使用replace。)
【解决方案2】:

如果您的字符串包含需要替换的模式,您可以使用 Matcher 类中的 appendReplacement 方法。

例如:

StringBuffer sb = new StringBuffer();
String[] tokens = {"first","plane tickets","friends"};
String text = "This is my 1 opportunity to buy 2 for my 3";
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(text);
for(int i=0; m.find(); i++) {
    m.appendReplacement(sb, tokens[i]);
}
m.appendTail(sb);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2012-04-26
    • 2014-03-14
    相关资源
    最近更新 更多