ios - 如何在 String Swift4 中交换两个字符?

标签 ios string swift4

in Swift4, the String is Collections. You will no longer use characters property on a string.

func swapCharacters(input:String,index1:Int,index2:Int)-> String { // logic to swap }

let input = "ABCDEFGH"

如果我用 (input,3,8) 调用函数,那么输出应该是

输出: ABCHEFGD

注意:在 Swift4 中,字符串是集合。

最佳答案

相当简单,因为 String 是一个集合:

func swapCharacters(input: String, index1: Int, index2: Int) -> String {
    var characters = Array(input)
    characters.swapAt(index1, index2)

    return String(characters)
}

let input = "ABCDEFGH"
print(swapCharacters(input: input, index1: 3, index2: 7)) //ABCHEFGD

或者,提供一个直接的类似数组的操作:

extension String {
    mutating func swapAt(_ index1: Int, _ index2: Int) {
        var characters = Array(self)
        characters.swapAt(index1, index2)
        self = String(characters)
    }
}

var input = "ABCDEFGH"
input.swapAt(3, 7)
print(input) //ABCHEFGD

关于ios - 如何在 String Swift4 中交换两个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981928/

相关文章:

iphone - UIImage 第一次加载时卡顿

ios - 如何知道当前正在显示 UITableView 的哪些单元格(行和部分)?

c# - .NET Marshal.PtrToStringUni(IntPtr) 与 new String(char*)

arrays - 在 Swift 4 中使用 reduce 时出现 "contextual closure type expects 2 arguments"错误

ios - 3D Touch 应用内 "Quick Actions"

ios检测无线变化

ios - iOS 上/tmp/文件夹中的照片什么时候过期

python - 将列表更改为字符串

c++ - 将字符串理解为 C++ 中的指针

ios - XLPagerTabStrip:不尊重状态栏