如何交换字符串中的两个字母?
我想改变字母的顺序。例如,有一个字符串“abc”,输出必须是“bac”。你能告诉我该怎么做吗?
先感谢您。
I want to switch the order of the letters. For example, there is a string "abc" and the output must be "bac". Can you please tell me how I can do it?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
String
可以隐式转换为IndexedSeq[Char]
的事实:此函数也可以正确处理小于 2 个字符的字符串,只需尝试以下操作:
You can use fact, that
String
can be converted toIndexedSeq[Char]
implicitly:This function also works correctly with strings, that smaller than 2 chars, just try this:
您的问题不清楚您是否想要反转字符串的东西,或者是否想要交换字符串中的两个字符的东西。这个答案是针对后者的。
当然,您可以将其概括为任何可以被视为 IndexedSeq 的内容:
Your question is not clear as to whether you want something which reverses a String, or whether you want something which swaps two characters in a String. This answer is for the latter
Of course you could generalize this into anything which can be viewed as an
IndexedSeq
:更实用的东西怎么样?
How about something more functional?