java 交换字符串中的两个字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26316674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swap two letters in a string
提问by Jainendra
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
.
我想交换一个字符串中的两个字母。例如,如果输入是W
和H
然后所有的出现W
在字符串应该被替换H
和的所有出现H
应改为W
。字符串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.
但我无法弄清楚如何交换字符。
采纳答案by PeterK
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
.
为了回应以下关于这种在String
. 这将无法工作,即使有一个*
在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, e.g. [
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("([\[\]\\+*?(){}^$])", "\\");
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();
}
回答by Arjuna
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;
}
回答by berdario
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
我敦促你不要使用 aCharacter
作为交换函数,因为它会破坏包含 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));
}
回答by 9000
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();
回答by August
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);
}
回答by Avinash Raj
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 ~
.
使用输入字符串中不存在的任何字符代替~
.