java中字符串数组更换某些字符串 [英] java replace certain string in array of strings

查看:130
本文介绍了java中字符串数组更换某些字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有在Java这个字符串数组

let's say I have this string array in java

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

但现在我想以取代在数组中字符串的所有空格以上20%,使它像这样

but now I want to replace all the whitespaces in the strings inside the array above to %20, to make it like this

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

我该怎么办呢?

推荐答案

遍历数组,并取代每个条目的EN codeD版本。

Iterate over the Array and replace each entry with its encoded version.

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

Like so, assuming that you are actually looking for URL-compatible Strings only:

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

要符合当前的Java,你必须指定的编码 - 但是,它应该永远是 UTF-8

To conform to current Java, you have to specify the encoding - however, it should always be UTF-8.

如果你想要一个更宽泛的版本,做什么其他人建议:

If you want a more generic version, do what everyone else suggests:

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

这篇关于java中字符串数组更换某些字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆