将字符串中所有的字符“+”替换为空字符在Java中。

huangapple go评论72阅读模式
英文:

Replace all the characters of "+" with empty character in string java

问题

我有一个字符串

String myString = "Hello+World+How are you";

如何将myString中所有的+替换为空字符


我尝试过: myString.replaceAll("\\+", " ");

我想找到的是: 用于匹配+的正则表达式,以便替换所有出现的地方

我想要实现的输出: Hello World How are you

英文:

I have a string

String myString = "Hello+World+How are you";

How to replace all "+" in myString with empty character


I tried with: myString.replaceAll("+"," ");

What I am trying to find: Regular expression for + so I can replace all occurrences

Output I am trying to achieve: Hello World How are you

答案1

得分: 2

尝试像这样使用:

myString.replace("+", " ");
英文:

try with like this

myString.replace("+"," ");

答案2

得分: 1

我通常使用 Pattern.quote(String)

String myString = "Hello+World+How are you";
String replaced = myString.replaceAll(Pattern.quote("+"), " ");

我认为如果以后需要修改正则表达式,使用这种方式会减少出错的可能性。

英文:

I usually use Pattern.quote(String)

String myString = "Hello+World+How are you";
String replaced = myString.replaceAll(Pattern.quote("+"), " ");

I think it is less error-prone if you (or someone else) need to modify the regexp later.

答案3

得分: 0

你应该在Java中的任何特殊字符前面使用 \\,这样你的代码将像这样用空格替换 +

myString.replaceAll("\\+", " ");

解释:\ 用于转义特殊字符,而 \ 本身也是一个特殊字符,这就是为什么我们必须使用 \\\\

英文:

You should use \\ with any special charachter in java,so your code will be like this to replace + with whitespace:

myString.replaceAll("\\+"," ");

Explanation: \ this is used to escape special characters,and this \ itself is a special character,that is why we have to use '\'.

huangapple
  • 本文由 发表于 2020年4月7日 11:59:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61072608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定