【问题标题】:Replace certain string in array of strings替换字符串数组中的某个字符串
【发布时间】:2012-02-18 18:55:56
【问题描述】:

假设我在 java 中有这个字符串数组

String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};

但现在我想将上面数组中的字符串中的所有空格替换为%20,让它变成这样

String[] test = {"hahaha%20lol", "jeng%20jeng%20jeng", "stack%20overflow"};

我该怎么做?

【问题讨论】:

  • 请注意,您的问题及其标题存在分歧 - 您的问题非常具体,而标题非常笼统。我在下面的回答涉及问题,而不是标题。
  • String.replace() ...毫无疑问的例子;-)

标签: java arrays string replace replaceall


【解决方案1】:

遍历数组并将每个条目替换为其编码版本。

像这样,假设您实际上只是在寻找与 URL 兼容的字符串:

for (int index =0; index < test.length; index++){
  test[index] = URLEncoder.encode(test[index], "UTF-8");
}

要符合当前的 Java,您必须指定编码 - 但是,它应该始终是 UTF-8

如果您想要更通用的版本,请按照其他人的建议:

for (int index =0; index < test.length; index++){
    test[index] = test[index].replace(" ", "%20");
}

【讨论】:

  • 请注意,令人讨厌的是,URLEncoder.encode(str) 已被弃用,取而代之的是其将编码类型作为第二个参数(应始终为“UTF-8”)的重载形式。
【解决方案2】:

这是一个简单的解决方案:

for (int i=0; i < test.length; i++) {
    test[i] = test[i].replaceAll(" ", "%20");
}

但是,您似乎正在尝试转义这些字符串以在 URL 中使用,在这种情况下,我建议您寻找一个可以为您执行此操作的库。

【讨论】:

  • 看我的回答,它是 JDK 的一部分。
  • 急于回答一个简单的问题并犯简单的错误:)
  • 另外,请参阅我对 maerics 的回答 re: replace and replaceall 的评论。
【解决方案3】:

尝试使用String#relaceAll(regex,replacement);未经测试,但这应该可以工作:

for (int i=0; i<test.length; i++) {
  test[i] = test[i].replaceAll(" ", "%20");
}

【讨论】:

  • 请注意,String#replace(target, replacement) 应该可以解决问题。 replacereplaceAll 相同,但不适用于 RegExes。
【解决方案4】:

对于每个字符串,你会做一个 replaceAll("\\s", "%20")

【讨论】:

    【解决方案5】:
    String[] test={"hahaha lol","jeng jeng jeng","stack overflow"};
                    for (int i=0;i<test.length;i++) {
                        test[i]=test[i].replaceAll(" ", "%20");
                    }
    

    【讨论】:

      【解决方案6】:

      直接来自 Java 文档...String java docs

      你可以做 String.replace('toreplace','replacement')。

      使用 for 循环遍历数组的每个成员。

      【讨论】:

        【解决方案7】:

        您可以改用IntStream。代码可能如下所示:

        String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};
        
        IntStream.range(0, test.length).forEach(i ->
                // replace non-empty sequences
                // of whitespace characters
                test[i] = test[i].replaceAll("\\s+", "%20"));
        
        System.out.println(Arrays.toString(test));
        // [hahaha%20lol, jeng%20jeng%20jeng, stack%20overflow]
        

        另见:How to replace a whole string with another in an array

        【讨论】:

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