how to switch two letters in a string?
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 adv开发者_如何学JAVAance.
You can use fact, that String
can be converted to IndexedSeq[Char]
implicitly:
def switch(s: String) = (s take 2 reverse) + (s drop 2)
This function also works correctly with strings, that smaller than 2 chars, just try this:
println(switch("abc")) // prints: bac
println(switch("ab")) // prints: ba
println(switch("a")) // prints: a
println(switch("")) // prints:
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
def swap(s : String, idx1 : Int, idx2 : Int) : String = {
val cs = s.toCharArray
val swp = cs(idx1)
cs(idx1) = cs(idx2)
cs(idx2) = swp
new String(cs)
}
Of course you could generalize this into anything which can be viewed as an IndexedSeq
:
def swap[A, Repr](repr : Repr, idx1 : Int, idx2 : Int)
(implicit bf: CanBuildFrom[Repr, A, Repr],
ev : Repr <%< IndexedSeqLike[A, Repr]) : Repr = {
val swp = repr(idx1)
val n = repr.updated(idx1, repr(idx2))
n.updated(idx2, swp)
}
How about something more functional?
import collection.breakOut
def swap(s:String, x:Int, y:Int):String = s.zipWithIndex.collect{
case (_,`x`) => s(y)
case (_,`y`) => s(x)
case (c,_) => c
}(breakOut)
精彩评论