简体   繁体   English

用 java 中的字符串中的字符替换字符序列

[英]Replacing char sequence with char from string in java

I want to replace all llpp with " < " char and all llqq with " > " from following string in a java code,我想用 java 代码中的以下字符串将所有llpp替换为 " < " char,并将所有llqq 替换为 " > ",

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请帮我

String targetString = sourceString.replace("llpp", "<").replace("llqq", ">");

The replace method replaces each instance of the first parameter with the second parameter. replace方法用第二个参数替换第一个参数的每个实例。 Since String s are immutable, you have to capture the result of the method by assigning it to a variable.由于String是不可变的,因此您必须通过将其分配给变量来捕获方法的结果。

Note that the above code will effect the replacements you want, though it won't format the code the way you've shown.请注意,上面的代码会影响您想要的替换,尽管它不会按照您显示的方式格式化代码。 Hopefully that's not something you need, since that would be significantly more complicated.希望这不是您需要的东西,因为那会更加复杂。

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

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

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