java 交换字符串,交换字符串中的两个字母

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

Edit

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("(?

.replace("\\*", "*");

}

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值