gpt4 book ai didi

swift - 如何修复 fatal error : Can't form a Character from an empty String

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:20 26 4
gpt4 key购买 nike

我是 Swift 的新手,调试花了我 1 小时,但我仍然不知道为什么会失败。

这是leetcode的一道题:反转字符串:

输入:“你好”

输出:“olleh”

还有我的代码:

import Foundation
class Solution {
func reverseString(_ s: String) -> String {
// initialize a new null string
var answer = ""
// get the length of the input string
var lengthOfString = s.characters.count
// add the character into the new string
for nums in 0...(lengthOfString-1){
var index = s.index(s.startIndex, offsetBy: lengthOfString)
answer.append(s[index])
lengthOfString-=1
}
return answer
}
}

let a = Solution()
let b = a.reverseString("hello")
print(b)

这是我错误的图片:

最佳答案

问题出在这个 block 中:

for nums in 0...(lengthOfString-1){
var index = s.index(s.startIndex, offsetBy: lengthOfString)
answer.append(s[index])
lengthOfString-=1
}
  1. 应该使用0..<lengthOfString范围。
  2. 您正在更改 lengthOfString 的值,这是一种非常糟糕的方式。

这是一个反转字符串的示例:

extension String {

subscript (i: Int) -> Character {
return self[characters.index(startIndex, offsetBy: i)]
}

subscript (i: Int) -> String {
return String(self[i] as Character)
}

func reverse() -> String {

let count = characters.count
if count == 0 { return "" }

var result = ""
for i in 0..<count {
result = self[i] + result
}

return result

}

}

let s = "hello"
s.reverse() // print: olleh

关于swift - 如何修复 fatal error : Can't form a Character from an empty String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421380/

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