如何在Swift中的特定索引处获取和设置字符串的字符

时间:2017-04-09 16:32:06

标签: arrays swift string character

我想用类似的东西 arrayString [firstString] [index] =“1”

但结果是: 无法通过下标分配:下标是get-only

并解释为什么以下代码 var arrayString:[String] = struct.strings

首先不允许比较[index] ==“0” 所以我需要使用var arrayString = struct.strings

1 个答案:

答案 0 :(得分:1)

根据您需要执行此操作的次数,最好只从字符串创建一个字符数组,并将其编入索引。

您可以只为您关心的字符串执行此操作:

let strings = ["abcdefg", "123", "qwerty"]
let characters = Array(strings[1].characters) // => ["1", "2", "3"]
print(characters[0]) // => "1"

或者如果您要对所有字符串进行大量访问,您可以提前将所有字符串预先转换为[Character],如下所示:

let strings = ["abcdefg", "123", "qwerty"]
let stringCharacters = strings.map{ Array(string.characters) }
/* [
       ["a", "b", "c", "d", "e", "f", "g"],
       ["1", "2", "3"],
       ["q", "w", "e", "r", "t", "y"]
   ] */
print(characters[1][0]) // => "1"

如果您想进行更改,只需将字符数组转换回String,并将其分配到任何您想要的地方:

var strings = ["abcdefg", "123", "qwerty"]
var characters = Array(strings[1].characters) // => ["1", "2", "3"]
characters[0] = "0"
strings[1] = String(characters)
print(strings) // => ["abcdefg", "023", "qwerty"]

此外,这是一个方便的扩展我用来改变字符串的许多字符:

extension String {
    mutating func modifyCharacters(_ closure: (inout [Character]) -> Void) {
        var characterArray = Array(self.characters)
        closure(&characterArray)
        self = String(characterArray)
    }
}


var string = "abcdef"

string.modifyCharacters {
    $0[0] = "1"
    $0[1] = "2"
    $0[2] = "3"
}

print(string)