gpt4 book ai didi

swift - 无法使用类型为 'append' 的参数列表调用 '(Range)'

转载 作者:可可西里 更新时间:2023-11-01 00:54:29 27 4
gpt4 key购买 nike

我看到的错误是标题:Cannot invoke 'append' with an argument list of type '(Range<String.Index>)'

在 Swift 中练习字符串交错时,我试图将一个字符串的子字符串附加到另一个字符串。 This other question covers将一个字符串附加到另一个字符串,这不是我的问题。 And this other question是抛出的完全不同的错误。 The Swift documentation on Strings and Characters 似乎没有涵盖将子字符串附加到字符串。

这一行(以及类似的一行)会引发错误。

result.append(str2.index(after: str2Index)..<str2.endIndex)

如何解决这个问题并将子字符串追加到字符串中?

var str1 = "abcde"
var str2 = "fgh"
print(str1) // prints 'abcde'
print(str2) // prints 'fgd'

var str1Index = str1.startIndex
var str2Index = str2.startIndex
var result = String()
var resultIndex = result.startIndex

while str1Index != str1.endIndex && str2Index != str2.endIndex {
result.insert(str1[str1Index],at: resultIndex)
str1Index = str1.index(after: str1Index)
resultIndex = result.index(after: resultIndex)

result.insert(str2[str2Index], at: resultIndex)
resultIndex = result.index(after: resultIndex)
str2Index = str2.index(after: str2Index)
}

if str1Index != str1.endIndex {
// This does not work, throws above mentioned error
result.append(str2.index(after: str2Index)..<str2.endIndex)
} else if str2Index != str2.endIndex {
// This does not work, throws above mentioned error
result.append(str1.index(after: str1Index)..<str1.endIndex)
}

print(result) // should print 'afbgchde'

PS,对我的算法的更正或评论也很感激:)

最佳答案

您可以使用 zip 对字符进行配对,使用 reduce(into:) 方法将它们连接成一个字符串,然后从最长的字符串中添加剩余的字符:

let str1 = "abcde"
let str2 = "fgh"
print(str1) // prints 'abcde'
print(str2) // prints 'fgh'
let str1Count = str1.count
let str2Count = str2.count
let result = zip(str1,str2).reduce(into: "") {
$0.append($1.0)
$0.append($1.1)
} + ( str1Count > str2Count ?
str1.suffix(str1Count-str2Count) :
str2.suffix(str2Count-str1Count) )

print(result) // 'afbgchde'

关于swift - 无法使用类型为 'append' 的参数列表调用 '(Range<String.Index>)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com