开发者

Java Character Switch

What's a r开发者_开发百科eally easy way to switch characters around in Java? Say I have the following:

String testString = "Hello World.";

// I know this doesn't work
testString = testString.replace('o', 'e');

I want to switch the 'e' with 'o' and I know this won't work... Please let me know what i need to do


 String testString = "Hello World.";
 String replacedString = testString.replaceAll("o", "~")
                                   .replaceAll("e","o")
                                   .replaceAll("~","e");

Okay as long as your string doesn't have a ~


You can build your own method that does that.

String SwitchCharOcurrences(String original, char x, char y) {
    char[] cArray = original.toCharArray();
    for(int i = 0; i < cArray.length; i++) {
        if(cArray[i] == x) {
            cArray[i] = y;
        } else if(cArray[i] == y) {
            cArray[i] = x;
        }
    }
    String result = new String (cArray);
    return result;
}


A simple solution would be to use a temp character:

testString = testString.replace('o', '@');
testString = testString.replace('e', 'o');
testString = testString.replace('@', 'e');

This may or may not be ideal, depending on the range of possible characters in the string, the length and how many times it needs to be executed. But for the example string it does work :-)


You can loop through the string and build the replacement string by examining each character. Something like this:

String testString = "Hello World.";
StringBuilder sb = new StringBuilder();
for (int i=0, length=testString.length(); i<length; i++) {
    char ch = testString.charAt(i);
    switch (ch) {
          case 'e':
              sb.append('o');
              break;
          case 'o':
              sb.append('e');
              break;
          default:
              sb.append(ch);
    }
}
String replacedString = sb.toString();

If you want to swap capital letters too you can do this:

String testString = "Hello World.";
StringBuilder sb = new StringBuilder();
for (int i=0, length=testString.length(); i<length; i++) {
    char ch = testString.charAt(i);
    switch (ch) {
          case 'e':
              sb.append('o');
              break;
          case 'E':
              sb.append('O');
              break;
          case 'o':
              sb.append('e');
              break;
          case 'O':
              sb.append('E');
              break;
          default:
              sb.append(ch);
    }
}
String replacedString = sb.toString();

But the switch statement is starting to get a bit long and messy. If you needed to add much more to it, it might get out of hand. A little refactoring might lead to this:

String testString = "Hello World.";

Map<Character,Character> replacementMap = new HashMap<Character,Character>();
replacementMap.put('e', 'o');
replacementMap.put('o', 'e');
replacementMap.put('E', 'O');
replacementMap.put('O', 'E');

StringBuilder sb = new StringBuilder();
for (int i=0, length=testString.length(); i<length; i++) {
    char ch = testString.charAt(i);
    Character replacement = replacementMap.get(ch);
    sb.append(replacement != null ? replacement : ch);
}
String replacedString = sb.toString();


Not with a single method call.

StringBuilder buf = new StringBuilder();
for(char c : testString.toCharArray()) // CharSequence should really be usable in such a loop
{
   switch(c) {
      case 'e': c = 'o'; break;
      case 'o': c = 'e'; break;
   }
    buf.append(c);
}
testString = buf.toString();

The canonical version would be this:

StringBuilder buf = new StringBuilder();

for(int i = 0; i <testString.length(); i++)
{
   char c = testString.charAt(i);
   switch(c) {
      case 'e': c = 'o'; break;
      case 'o': c = 'e'; break;
   }
    buf.append(c);
}
testString = buf.toString();

Could someone benchmark those two versions for different String lengths?


This may be not optimal, but relatively easy ;)

String testString = "Hello World.";

testString = testString.replace('o', '\u0001');
testString = testString.replace('e', 'o');
testString = testString.replace('\u0001', 'e');

The idea is to take a character that you are sure is not used in string and use it as temporary replace.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜