替换字符串数组中的某些字符串 [英] Replace certain string in array of strings

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

问题描述

假设我在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"};

我该怎么做?

推荐答案

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

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");
}

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

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