简体   繁体   English

在字符串中交换两个字母

[英]Swap two letters in a string

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 . 例如,如果输入为WH那么字符串中W所有出现都应该被H替换,并且所有出现的H应该被W替换。 String WelloHorld will become HelloWorld . String WelloHorld将成为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. 但我无法弄清楚如何交换字符。

public String getSwappedString(String s)
{
char ac[] = s.toCharArray();
for(int i = 0; i < s.length(); i++)
{
   if(ac[i] == 'H')
     ac[i]='W';
   else if(ac[i] == 'W')
     ac[i] = 'H'; 
}

s = new String(ac);
return s;
}

With Java8 it's truly simple 使用Java8,它真的很简单

static String swap(String str, String one, String two){
    return Arrays.stream(str.split(one, -1))
        .map(s -> s.replaceAll(two, one))
        .collect(Collectors.joining(two));
}

Usage example: 用法示例:

public static void main (String[] args){
    System.out.println(swap("𐌰𐌱𐌲", "𐌰", "𐌲"));
}

I urge you not to use a Character for the swap function, since it will break strings containing letters outside the BMP 我建议你不要在交换函数中使用Character ,因为它会破坏包含BMP之外字母的字符串

In case you want to extend this to work with arbitrary Strings (not only letters), you can just quote the supplied strings: 如果你想扩展它以使用任意字符串(不仅仅是字母),你可以引用提供的字符串:

static String swap(String str, String one, String two){
    String patternOne = Pattern.quote(one);
    String patternTwo = Pattern.quote(two);
    return Arrays.stream(str.split(patternOne, -1))
        .map(s -> s.replaceAll(patternTwo, one))
        .collect(Collectors.joining(two));
}

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");

Edit 编辑

In response to some of the concerns below regarding the correctness of this method of swapping characters in a String . 响应于一些在下面关于在交换字符的这个方法的正确性的关注String This will work, even when there is a * in the String already. 这将起作用,即使String已存在* However, this requires the additional steps of first escaping any occurrence of * and un-escaping these before returning the new String . 但是,这需要额外的步骤:首先转义任何出现的*并在返回新String之前取消它们。

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

}

Edit 2 编辑2

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, eg [ and ] and takes into account concerns about using char primitives for manipulating String objects. 在阅读了其他一些答案后,新版本不仅适用于Java 8,它可以替换需要在正则表达式中转义的字符,例如[]并考虑到使用char原语操作String对象。

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();

}

A slightly nicer version of the string-scanning approach, without explicit arrays and index access: 一个稍微好一点的字符串扫描方法,没有显式数组和索引访问:

StringBuilder sb = new StringBuilder();
for (char c : source_string.toCharArray()) {
  if (c == 'H') sb.append("W");
  else if (c == 'W') sb.append("H");
  else sb.append(c);
}
return sb.toString();

You could iterate over the String's character array, and swap whenever you see either of the characters: 您可以迭代String的字符数组,并在看到任何一个字符时进行交换:

private static String swap(String str, char one, char two) {
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == one) {
            chars[i] = two;
        } else if (chars[i] == two) {
            chars[i] = one;
        }
    }
    return String.valueOf(chars);
}

You could try this code also. 你也可以尝试这个代码。

System.out.println("WelloHorld".replaceAll("W", "H~").replaceAll("H(?!~)", "W").replaceAll("(?<=H)~", ""));

Output: 输出:

HelloWorld

Use any character which isn't present in the input string instead of ~ . 使用输入字符串中不存在的任何字符而不是~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM