假设我在java中有这个字符串数组
String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};
但现在我想将上面数组中字符串中的所有空格替换为%20
,使其像这样
String[] test = {"hahaha%20lol", "jeng%20jeng%20jeng", "stack%20overflow"};
我该怎么做?
假设我在java中有这个字符串数组
String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};
但现在我想将上面数组中字符串中的所有空格替换为%20
,使其像这样
String[] test = {"hahaha%20lol", "jeng%20jeng%20jeng", "stack%20overflow"};
我该怎么做?
遍历 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");
}
这是一个简单的解决方案:
for (int i=0; i < test.length; i++) {
test[i] = test[i].replaceAll(" ", "%20");
}
但是,您似乎正在尝试转义这些字符串以在 URL 中使用,在这种情况下,我建议您寻找一个可以为您执行此操作的库。
尝试使用String#relaceAll(regex,replacement)
;未经测试,但这应该工作:
for (int i=0; i<test.length; i++) {
test[i] = test[i].replaceAll(" ", "%20");
}
对于每个 String 你会做一个 replaceAll("\\s", "%20")
String[] test={"hahaha lol","jeng jeng jeng","stack overflow"};
for (int i=0;i<test.length;i++) {
test[i]=test[i].replaceAll(" ", "%20");
}
直接从 Java 文档中提取... String java docs
你可以做 String.replace('toreplace','replacement')。
使用 for 循环遍历数组的每个成员。
你可以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]