Java中如何交换字符串字符?
如何交换字符串
中的两个字符? 例如,“abcde”
将变为“bacde”
。
How can I swap two characters in a String
? For example, "abcde"
will become "bacde"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
由于
String
对象是不可变的,因此通过toCharArray
,交换字符,然后从创建一个新的
通过String
>char[]String(char[])
构造函数可以工作。以下示例交换第一个和第二个字符:
结果:
Since
String
objects are immutable, going to achar[]
viatoCharArray
, swapping the characters, then making a newString
fromchar[]
via theString(char[])
constructor would work.The following example swaps the first and second characters:
Result:
“在”字符串中,你不能。 字符串是不可变的。 您可以使用以下命令轻松创建第二个字符串:
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
这个问题已经被回答过几次了,但这里还有一个只是为了好玩:-)
This has been answered a few times but here's one more just for fun :-)
String.toCharArray()< /a> 将为您提供代表该字符串的字符数组。
您可以在不更改原始字符串的情况下更改此设置(交换所需的任何字符),然后使用 字符串(char[])。
请注意,字符串是不可变的,因此您必须创建一个新的字符串对象。
String.toCharArray() will give you an array of characters representing this string.
You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).
Note that strings are immutable, so you have to create a new string object.
这是用于递归交换 java 字符的 java 示例代码。您可以在 http://java2novice.com/java-interview-programs/string-reverse-recursive/
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/
String.replaceAll() 或 ReplaceFirst()
链接到 JavaDocs 字符串 API
String.replaceAll() or replaceFirst()
Link to the JavaDocs String API
这是使用
StringBuilder
的解决方案。 它支持使用填充字符填充字符串长度不均匀的结果字符串。 正如您所猜测的,该方法是为十六进制半字节交换而设计的。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.我认为这应该有帮助。
I think this should help.
如果您要传递的字符串是“Random”,那么您想交换“R”和“m”,那么这里的originalStr将是Random,inter1将是R,inter2将是m。
If the string that you want to pass on is "Random" then you want to interchange "R" and "m" then here the originalStr will be Random, inter1 will be R and inter2 will be m.
以下代码行将交换
str
中的前两个字符:The following line of code will swap the first two characters in
str
: