如何在 Java 中交换字符串字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/956199/
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
How to swap String characters in Java?
提问by user107023
How can I swap twocharacters in a String? For example, "abcde"will become "bacde".
如何在 a 中交换两个字符String?例如,"abcde"将成为"bacde"。
回答by AgileJon
String.replaceAll() or replaceFirst()
String.replaceAll() 或 replaceFirst()
String s = "abcde".replaceAll("ab", "ba")
Link to the JavaDocs String API
链接到 JavaDocs字符串 API
回答by toolkit
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
'在'一个字符串中,你不能。字符串是不可变的。您可以使用以下命令轻松创建第二个字符串:
String second = first.replaceFirst("(.)(.)", "");
回答by coobird
Since Stringobjects are immutable, going to a char[]via toCharArray, swapping the characters, then making a new Stringfrom char[]via the String(char[])constructor would work.
由于String对象是不可改变的,去一个char[]通过toCharArray,调换角色,然后又做了新的String从char[]通过String(char[])构造函数会工作。
The following example swaps the first and second characters:
以下示例交换第一个和第二个字符:
String originalString = "abcde";
char[] c = originalString.toCharArray();
// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
System.out.println(originalString);
System.out.println(swappedString);
Result:
结果:
abcde
bacde
回答by Brian Agnew
String.toCharArray()will give you an array of characters representing this string.
String.toCharArray()会给你一个代表这个字符串的字符数组。
You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).
您可以在不更改原始字符串的情况下更改此设置(交换您需要的任何字符),然后使用String(char[])创建一个新字符串。
Note that strings are immutable, so you have to create a new string object.
请注意,字符串是不可变的,因此您必须创建一个新的字符串对象。
回答by Brian Agnew
This has been answered a few times but here's one more just for fun :-)
这已经回答了几次,但这里还有一个只是为了好玩:-)
public class Tmp {
public static void main(String[] args) {
System.out.println(swapChars("abcde", 0, 1));
}
private static String swapChars(String str, int lIdx, int rIdx) {
StringBuilder sb = new StringBuilder(str);
char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
sb.setCharAt(lIdx, r);
sb.setCharAt(rIdx, l);
return sb.toString();
}
}
回答by Java2novice
Here is java sample code for swapping java chars recursively.. You can get full sample code at http://java2novice.com/java-interview-programs/string-reverse-recursive/
这是用于递归交换java字符的java示例代码..您可以在http://java2novice.com/java-interview-programs/string-reverse-recursive/获得完整的示例代码
public String reverseString(String str){
if(str.length() == 1){
return str;
} else {
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
回答by Prem
import java.io.*;
class swaping
{
public static void main(String args[])
{
String name="premkumarg";
int len=name.length();
char[] c = name.toCharArray();
for(int i=0;i<len-1;i=i+2)
{
char temp= c[i];
c[i]=c[i+1];
c[i+1]=temp;
}
System.out.println("Swapping string is: ");
System.out.println(c);
}
}
回答by Andrey
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
回答by Russell
static String string_swap(String str, int x, int y)
{
if( x < 0 || x >= str.length() || y < 0 || y >= str.length())
return "Invalid index";
char arr[] = str.toCharArray();
char tmp = arr[x];
arr[x] = arr[y];
arr[y] = tmp;
return new String(arr);
}
回答by Markus L
Here's a solution with a StringBuilder. It supports padding resulting strings with uneven string length with a padding character. As you've guessed this method is made for hexadecimal-nibble-swapping.
这是一个带有StringBuilder. 它支持使用填充字符填充字符串长度不均匀的结果字符串。正如您已经猜到的那样,此方法是为十六进制半字节交换而设计的。
/**
* Swaps every character at position i with the character at position i + 1 in the given
* string.
*/
public static String swapCharacters(final String value, final boolean padding)
{
if ( value == null )
{
return null;
}
final StringBuilder stringBuilder = new StringBuilder();
int posA = 0;
int posB = 1;
final char padChar = 'F';
// swap characters
while ( posA < value.length() && posB < value.length() )
{
stringBuilder.append( value.charAt( posB ) ).append( value.charAt( posA ) );
posA += 2;
posB += 2;
}
// if resulting string is still smaller than original string we missed the last
// character
if ( stringBuilder.length() < value.length() )
{
stringBuilder.append( value.charAt( posA ) );
}
// add the padding character for uneven strings
if ( padding && value.length() % 2 != 0 )
{
stringBuilder.append( padChar );
}
return stringBuilder.toString();
}

