开发者

String replace in Java

开发者 https://www.devze.com 2022-12-15 03:26 出处:网络
I currently have a string which contains the characters A, B and C for example the string looks like

I currently have a string which contains the characters A, B and C for example the string looks like

"A some other random stuff B C"

the other random stuff doesn't contain A, B or C I want to replace the A, B开发者_开发知识库 & C with 'A', 'B' and 'C' respectively what's the best way to do that currently I'm doing:

String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")


cletus' answer works fine if A, B and C are those exact single characters, but not if they could be longer strings and you just called them A, B and C for example purposes. If they are longer strings you need to do:

String input = "FOO some other random stuff BAR BAZ";
String output = input.replaceAll("FOO|BAR|BAZ", "'$0'");

You will also need to escape any special characters in FOO, BAR and BAZ so that they are not interpreted as special regular expression symbols.


Use a regular expression:

String input = "A some other random stuff B C";
String output = input.replaceAll("[ABC]", "'$0'");

Output:

'A' some other random stuff 'B' 'C'


Have a look at StringUtils from Apache Commons Lang and its various replace methods.


I think regex is not really suitable if those are fairly complex strings.

Consider just wrapping it in your own utility method taking arrays or lists as arguments.

public static String replace(String string, String[] toFind, String[] toReplace) {
    if (toFind.length != toReplace.length) {
        throw new IllegalArgumentException("Arrays must be of the same length.");
    }
    for (int i = 0; i < toFind.length; i++) {
        string = string.replace(toFind[i], toReplace[i]);
    }
    return string;
}

Maybe there's already one in the Apache Commons or Google Code. Give it a look if you prefer 3rd party API's above homegrown stuff.

Edit: why downvoting a technically correct but a in your opinion not preferred answer? Just don't upvote.


The other peoples answers are better, but under the assumption you are trying to learn, I wanted to point out the problems with your original code.

Here would be a "Fixed" version of what you are trying to do (Using your style, which was close) and the things you need to do to make it work:

public String quoteLetters(String s)
{
    return s.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'");
}

Here are the problems you had:

  • Replace is a method, not a static function, so you have to call it on an instance of String, not String itself.
  • Replace returns an instance of the new string, it cannot modify the original string. In my code, I'm "Returning" the new string, s remains unmodified.
  • If this is homework, you should have tagged it as such.
  • Don't chain them like I did--the other answers are better because mine will actually create 3 new strings and then immediately destroy them.
0

精彩评论

暂无评论...
验证码 换一张
取 消