6

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

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

但现在我想将上面数组中字符串中的所有空格替换为%20,使其像这样

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

我该怎么做?

4

7 回答 7

10

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

像这样,假设您实际上只是在寻找与 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");
}
于 2012-01-25T15:31:32.267 回答
4

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

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

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

于 2012-01-25T15:31:40.643 回答
3

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

for (int i=0; i<test.length; i++) {
  test[i] = test[i].replaceAll(" ", "%20");
}
于 2012-01-25T15:32:08.367 回答
1

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

于 2012-01-25T15:31:47.510 回答
1
String[] test={"hahaha lol","jeng jeng jeng","stack overflow"};
                for (int i=0;i<test.length;i++) {
                    test[i]=test[i].replaceAll(" ", "%20");
                }
于 2012-01-25T15:33:19.347 回答
0

直接从 Java 文档中提取... String java docs

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

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

于 2012-01-25T15:33:32.173 回答
0

你可以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]

另请参阅:如何将整个字符串替换为数组中的另一个字符串

于 2020-12-20T15:33:31.743 回答