【问题标题】:Replace string to values from array将字符串替换为数组中的值
【发布时间】:2017-11-12 09:50:32
【问题描述】:

我有一个字符串The quick * fox jumps * the * dog,我有一个字符串数组String[] array = {"brown", "over", "lazy"}

将所有*替换为数组中的字符串的最佳方法是什么,然后第一个*必须替换为array[0]元素,第二个*array[1]等当然解决方案必须允许N替换数组中的 N 个元素。

【问题讨论】:

  • * 是强制性的吗? (而不是使用%s
  • @Marvin 是的,我需要*
  • 如果数组条目少于*会发生什么?
  • @Marvin 在我的代码中这是不可能的。

标签: java arrays regex string


【解决方案1】:
String.format("The quick * fox jumps * the * dog".replace("*", "%s"), array);
> The quick brown fox jumps over the lazy dog

replace *%s 并使用 String.formatparameters,这种方式有效。

查看更多:How to format strings in Java

【讨论】:

  • 赞成作为最简单解决方案,对“最佳方式”的一种有效解释。
  • replaceAll 使用正则表达式语法,其中 * 具有特殊含义。我们这里不需要正则表达式,replace 方法会更好,因为它不使用正则表达式语法(它会自动转义它)并且还会替换所有出现的搜索字符串。
  • 谢谢@Pshemo :)
【解决方案2】:

使用 Java regex 库的appendReplacement 功能:

StringBuffer res = new StringBuffer();
Pattern regex = Pattern.compile("[*]");
Matcher matcher = regex.matcher("Quick * fox jumps * the * dog");
int pos = 0;
String[] array = {"brown", "over", "lazy"};
while (matcher.find()) {
    String replacement = pos != array.length ? array[pos++] : "*";
    matcher.appendReplacement(res, replacement);
} 
matcher.appendTail(res);

Demo.

【讨论】:

  • 如果pos == array.length,则退出循环,appendTail() 将追加其余部分。比用* 替换* 更快。 --- 注意,甚至允许在迭代期间跳过对appendReplacement() 的调用,例如如果您跳过每个偶数 *,则结果只会替换奇数 * 标记。
  • @Andreas 我相信 OP 会弄清楚当有额外的占位符时会发生什么的细节。我只是想向他展示不会崩溃的代码。
【解决方案3】:
for (String x : array) {
    yourString = yourString.replaceFirst("\\*", x);
}

【讨论】:

  • replaceFirst 使用正则表达式语法,其中* 是元字符。为了使其字面化,我们需要对其进行转义。
【解决方案4】:

如果“最佳方式”是指性能,则使用indexOf() 循环并使用StringBuilder 构建结果。

如果这就是您所说的“最佳方式”,其他答案已经涵盖了“简单”(即更少的代码)。

String input = "The quick * fox jumps * the * dog";
String[] array = {"brown", "over", "lazy"};

StringBuilder buf = new StringBuilder();
int start = 0;
for (int i = 0, idx; i < array.length; i++, start = idx + 1) {
    if ((idx = input.indexOf('*', start)) < 0)
        break;
    buf.append(input.substring(start, idx)).append(array[i]);
}
String output = buf.append(input.substring(start)).toString();

System.out.println(output);

输出

The quick brown fox jumps over the lazy dog

此代码将静默接受数组中过多或过少的值。

【讨论】:

    【解决方案5】:

    编写一个 for 循环遍历字符串 The quick * fox jumps * the * dog 中的每个字符,每次遇到 * 时,选择数组的下一个元素,同时保持当前索引。

    String text = "The quick * fox jumps * the * dog";
    String[] elements = {"brown", "over", "lazy"};
    
    int idx = 0;
    StringBuilder result = new StringBuilder();
    for (char c : text.toCharArray()) {
        if (c == '*')
            result.append(elements[idx++]);
        else
            result.append(String.valueOf(c));
    }
    

    【讨论】:

      【解决方案6】:

      在所有情况下都需要重构字符串,最好的方法是使用StringBuilder

      两种方法:

      第一

      • 按字符迭代字符串,如果不是*,则将其添加到StringBuilder
      • 如果字符是*,则在表示指向字符串数组的指针的索引变量处添加字符串
      • 将索引增加 1。

      第二

      • 使用split() 方法将原始字符串拆分为*,这将为您提供一个原始字符串的字符串数组,不带*
      • 同时在两个数组上迭代一次,添加拆分数组的项,然后在第二个替换数组处添加相应的索引。

      【讨论】:

        猜你喜欢
        • 2013-11-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 2012-04-26
        • 2021-12-26
        • 2014-02-01
        • 2012-11-25
        • 1970-01-01
        相关资源
        最近更新 更多