String replace with Java

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

"A some other random stuff B C"

other random stuff does not contain A, B or CI that want to replace A, B and C with "A", "B" and "C" respectively, which is the best way to do this at the moment I'm doing

String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")
+5
source share
5 answers
Answer to

cletus works great if A, B and C are exact single characters, but not if they can be long strings, and you just call them A, B and C, for example, for purposes. If they are longer than the lines, you need to do:

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

- FOO, BAR BAZ, .

+16

:

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

:

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

StringUtils Apache Commons Lang replace.

+3

, regex , .

, , .

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;
}

, Apache Commons Google Code. , API .

: , , , ? .

+2

, , , .

"" , ( , ) , , :

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

, :

  • Replace - , , String, String.
  • , . "" , s .
  • , .
  • , , , 3 , .
+1
source

All Articles