var str: String = "sometext"
for i in str.characters.indices
{
str[i] = "c"
}
print(str)
,我發現了以下錯誤:
error: cannot assign through subscript: subscript is get-only
如何使用Swift修改字符串中的單個字符?
var str: String = "sometext"
for i in str.characters.indices
{
str[i] = "c"
}
print(str)
,我發現了以下錯誤:
error: cannot assign through subscript: subscript is get-only
如何使用Swift修改字符串中的單個字符?
您收到此錯誤,因爲斯威夫特字符串的下標方法得到,只喜歡它在你的警告說。 這與Array不同。
陣列:
array[0]
✅
array[0] = 0
✅
字符串:
str[0]
❌
str[0] = "0"
❌
str[str.startIndex.advancedBy(0)]
✅
使用replaceRange
爲完成你的任務。
例子:
var value = "green red blue"
value.replaceRange(value.startIndex.advancedBy(
6)..<value.startIndex.advancedBy(6 + 3),
with: "yellow")
print(value)
結果:
green yellow blue
也可以看看從奧萊Begemann這一高超的博客文章誰解釋斯威夫特字符串是如何工作的很詳細。你也會找到答案爲什麼你不能在Swift字符串上使用下標方法。
Because of the way Swift strings are stored, the String type does not support random access to its Characters via an integer index — there is no direct equivalent to NSStringʼs characterAtIndex: method. Conceptually, a String can be seen as a doubly linked list of characters rather than an array. Article Link
謝謝你,很好的回答! –
在一些情況下,可能優選的是將字符串轉換爲一個陣列,變異,然後轉換回爲String,例如:
var chars = Array("sometext".characters)
for i in 0..<chars.count {
chars[i] = "c"
}
let string = String(chars)
優點包括:
缺點包括:
挑選你的毒藥:)
你想只用'C'的字符串結束了? – Eendje
@Eendje它只是爲了示範,但在這種情況下,是的。 –