java 用java中的字符串中的字符替换字符序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7089924/
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
Replacing char sequence with char from string in java
提问by Soniya
I want to replace all llppwith "<" char and all llqqwith ">" from following string in a java code,
我想,以取代所有llpp与“ <”字符和所有llqq与“ >”从在Java代码下面的字符串,
llpphtmlllqq
llppheadllqqllpptitlellqqCompany Name-Companyllpp/titlellqqllpp/headllqq
llppbodyllqqSome text herellpp/bodyllqq
llpp/htmlllqq
I have above string and i want it to be
我有上面的字符串,我希望它是
<html>
<head><title>Company Name-Company</title></head>
<body>Some text here</body>
</html>
please help me
请帮我
回答by dlev
String targetString = sourceString.replace("llpp", "<").replace("llqq", ">");
The replace
method replaces each instance of the first parameter with the second parameter. Since String
s are immutable, you have to capture the result of the method by assigning it to a variable.
该replace
方法用第二个参数替换第一个参数的每个实例。由于String
s 是不可变的,因此您必须通过将其分配给变量来捕获该方法的结果。
Note that the above code will effect the replacements you want, though it won'tformat the code the way you've shown. Hopefully that's not something you need, since that would be significantly more complicated.
请注意,上面的代码会影响您想要的替换,但它不会按照您显示的方式格式化代码。希望这不是您需要的东西,因为那会复杂得多。
回答by MByD
String newString = oldString.replace("llpp", "<").replace("llqq", ">");
replace(CharSequence, CharSequence)
is available from Java 5. before that you had to use replaceAll
which takes regular expression as first parameter.
replace(CharSequence, CharSequence)
可从 Java 5 获得。在此之前,您必须使用replaceAll
which 将正则表达式作为第一个参数。
回答by bobby
If in java have a look at String's replace function http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29
如果在java中查看String的替换函数http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang .CharSequence%29