交换字符串中出现的2个符号

时间:2017-08-25 12:36:17

标签: java string replace

我有一个字符串,我想用Dots替换所有Kommas和Komma所有Dots

我目前的解决方案:

public String swapCommaDot(String toReplace){
String randomSequence = "AKP5W4TwcbxvkHUKwGTS"; 
//random.org generated Password
// longer sequence = lesser risk that this sequence is contained in toReplace
toReplace.replaceAll(",",randomSequence);
toReplace.replaceAll("\\.",",");
toReplace.replaceAll(randomSequence,"\\.");
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

public static  void swap(String s){
        int index=0;
        char[] chars=s.toCharArray();
        for(char c:chars){

            if('.'==c)
            chars[index]=',';
            else if(','==c){
                chars[index]='.';
            }
            index++;

        }
        System.out.println(String.valueOf(chars));
    }