简体   繁体   English

从字符串中删除字符

[英]Removing characters from string

Say have a string: 说一个字符串:

String x = "0: 0->1 -2.00";

And I want to remove certain characters, specifically : : > and a few others so that string is now: 我想删除某些字符,特别是: : >和其他几个人,这样的字符串现在是:

0 1 -2.00

Is there a simple way to do this? 有没有简单的方法可以做到这一点?

To remove just one type of character, you can do this. 要仅删除一种类型的字符,可以执行此操作。

myString = myString.replace(":", "");

For more complicated cases, you might need a regular expression, in which case, you'll use replaceAll instead of replace , but you have to be careful about escaping any characters that are "special" in a regular expression. 对于更复杂的情况,您可能需要一个正则表达式,在这种情况下,您将使用replaceAll而不是replace ,但是您必须谨慎转义正则表达式中“特殊”的任何字符。

myString = myString.replaceAll("->|:", "");

As an example, if you wanted to remove -> and : and + , you might write 例如,如果要删除->:+ ,可以编写

myString = myString.replaceAll("->|:|\\+", "");

because + is special and needs to be escaped with a backslash. 因为+是特殊字符,需要用反斜杠转义。

  x = x.replace(":", "");
  x = x.replace("->", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM