java android从字符串中替换多个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9989945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
android replace multiple characters from a string
提问by Tuffy G
I know that this may be an amateur question but for some reason I can't remember how to do this. I have 2 strings.
我知道这可能是一个业余问题,但出于某种原因,我不记得该怎么做。我有 2 个字符串。
String s ="[";
String q ="]";
if my text contains any of these i want to replace it with w
which is:
如果我的文本包含其中任何一个,我想将其替换w
为:
String w = "";
I have tried the following:
我尝试了以下方法:
output=String.valueOf(profile.get("text")).replace(s&&q, w);
from what i understand if of S([) and any of Q(]) are in text they will be replaced with w. my problem is getting the 2. if i only try and replace one then it will work. otherwise it wont.
据我所知,如果 S([) 和任何 Q(]) 在文本中,它们将被替换为 w。我的问题是得到 2。如果我只尝试更换一个,那么它会起作用。否则它不会。
any help would be appreciated
任何帮助,将不胜感激
回答by noob
You can nest them up too:
你也可以嵌套它们:
output=String.valueOf(profile.get("text")).replace(s, w).replace(q, w);
回答by hmjd
I think this is what you mean:
我想这就是你的意思:
String s = "abc[def]";
String w = "hello";
System.out.println(s.replaceAll("\[|\]", w));
Outputs abchellodefhello
.
输出abchellodefhello
。
String.replaceAll()
accepts a regular expression as its first argument, which would provide the flexibility required.
String.replaceAll()
接受一个正则表达式作为它的第一个参数,这将提供所需的灵活性。
回答by Shankar Agarwal
String s = "[";
String q = "]";
String w = "{";
String as = "sdada[sad]sdas";
String newstring = as.replace(s, w).replace(q,w);
Toast.makeText(_activity,newstring,Toast.LENGTH_LONG).show();
This is the working code for you...
这是您的工作代码...
回答by bos
If you read on http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace%28char,%20char%29you will see that it takes two char objects as an argument. The construction "s && q" and "s || q" are both illegal and gibberish. Think of it: what exactly would the logical operation ("foo" && "bar") return?
如果您在http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace%28char,%20char%29 上阅读,您将看到它需要两个 char 对象作为一个论点。构造“s && q”和“s || q”都是非法的和胡言乱语。想一想:逻辑运算 ("foo" && "bar") 到底会返回什么?
Do this:
做这个:
output = String.valueOf(profile.get("text")).replace(q, w).replace(s, w);
This will yield what you want.
这将产生你想要的。
回答by Ravi1187342
check out this
看看这个
String s ="[";
String q ="]";
String w = "";
String output=w.replace("[", w);
output=output.replace("]", w);
回答by Deva
try using replaceAllmethod from java.lang.String.
尝试使用java.lang.String 中的replaceAll方法。