交换字符串中的两个字母 [英] Swap two letters in a string

查看:1340
本文介绍了交换字符串中的两个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串中交换两个字母。例如,如果输入是 W H 那么所有出现的 W 应替换为 H ,所有出现的 H 应替换为 w ^ 。字符串 WelloHorld 将成为 HelloWorld

I want to swap two letters in a string. For example, if input is W and H then all the occurrences of W in string should be replaced by H and all the occurrences of H should be replaced by W. String WelloHorld will become HelloWorld.

我知道如何替换单个字符:

I know how to replace single char:

str = str.replace('W', 'H');

但我无法弄清楚如何交换字符。

But I am not able to figure out how to swap characters.

推荐答案

您可能需要三次替换调用才能完成此操作。

You would probably need three replace calls to get this done.

第一个将一个字符更改为中间值,第二个将第一个替换为第二个,第三个将第二个替换为第二个替换中间值。

The first one to change one of the characters to an intermediate value, the second to do the first replace, and the third one to replace the intermediate value with the second replacement.

String str = "Hello World";

str = star.replace("H", "*").replace("W", "H").replace("*", "W");

修改

回答以下关于在 String 中交换字符的方法的正确性的一些问题。即使 String 中已存在 * ,这也可以正常工作。但是,这需要额外的步骤:首先转义任何 * ,并在返回新的 String 之前取消转义这些步骤。

In response to some of the concerns below regarding the correctness of this method of swapping characters in a String. This will work, even when there is a * in the String already. However, this requires the additional steps of first escaping any occurrence of * and un-escaping these before returning the new String.

public static String replaceCharsStar(String org, char swapA, char swapB) {
    return org
            .replace("*", "\\*")
            .replace(swapA, '*')
            .replace(swapB, swapA)
            .replaceAll("(?<!\\\\)\\*", "" + swapB)
            .replace("\\*", "*");

}

编辑2

在阅读了其他一些答案之后,一个不仅适用于Java 8的新版本可以替换需要在正则表达式中转义的字符,例如 [] 并考虑使用 char 的顾虑用于操作 String 对象的原语。

After reading through some the other answers, a new version, that doesn't just work in Java 8, works with replacing characters which need to be escaped in regex, e.g. [ and ] and takes into account concerns about using char primitives for manipulating String objects.

public static String swap(String org, String swapA, String swapB) {
    String swapAEscaped = swapA.replaceAll("([\\[\\]\\\\+*?(){}^$])", "\\\\$1");
    StringBuilder builder = new StringBuilder(org.length());

    String[] split = org.split(swapAEscaped);

    for (int i = 0; i < split.length; i++) {
        builder.append(split[i].replace(swapB, swapA));
        if (i != (split.length - 1)) {
            builder.append(swapB);
        }
    }

    return builder.toString();

}

这篇关于交换字符串中的两个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆