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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:34:23  来源:igfitidea点击:

Replacing char sequence with char from string in java

javahtml

提问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 replacemethod replaces each instance of the first parameter with the second parameter. Since Strings are immutable, you have to capture the result of the method by assigning it to a variable.

replace方法用第二个参数替换第一个参数的每个实例。由于Strings 是不可变的,因此您必须通过将其分配给变量来捕获该方法的结果。

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 replaceAllwhich takes regular expression as first parameter.

replace(CharSequence, CharSequence)可从 Java 5 获得。在此之前,您必须使用replaceAllwhich 将正则表达式作为第一个参数。

回答by Michael-O