gpt4 book ai didi

swift - 在 Swift 中获取字符串的第 n 个字符

转载 作者:行者123 更新时间:2023-11-30 13:47:35 27 4
gpt4 key购买 nike

如何获取字符串的第n个字符?我尝试了括号([])访问器,但没有成功。

var string = "Hello, world!"

var firstChar = string[0] // Throws error

ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

最佳答案

注意:请参阅Leo Dabus' answer以便正确实现 Swift 4 和 Swift 5。

Swift 4 或更高版本

Swift 4 中引入了 Substring 类型来创建子字符串通过与原始字符串共享存储来更快、更高效,这就是下标函数应该返回的内容。

尝试一下 here

extension StringProtocol {
subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
subscript(range: Range<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: ClosedRange<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}

要将Substring转换为String,您可以简单地执行 String(string[0..2]),但只有在以下情况下才应该这样做您打算保留子字符串。不然就更了有效地将其保留为子字符串

如果有人能找到合并的好方法那就太好了这两个扩展合二为一。我尝试扩展 StringProtocol没有成功,因为那里不存在 index 方法。 注意:这个答案已经被编辑过,它已经正确实现,现在也适用于子字符串。只需确保使用有效范围以避免在为 StringProtocol 类型添加下标时崩溃。对于使用不会因超出范围值而崩溃的范围的下标,您可以使用此 implementation

<小时/>

为什么这不是内置的?

错误消息显示“请参阅文档注释进行讨论”。苹果在文件UnavailableStringAPIs.swift中提供了以下解释:

Subscripting strings with integers is not available.

The concept of "the ith character in a string" has different interpretations in different libraries and system components. The correct interpretation should be selected according to the use case and the APIs involved, so String cannot be subscripted with an integer.

Swift provides several different ways to access the character data stored inside strings.

  • String.utf8 is a collection of UTF-8 code units in the string. Use this API when converting the string to UTF-8. Most POSIX APIs process strings in terms of UTF-8 code units.

  • String.utf16 is a collection of UTF-16 code units in string. Most Cocoa and Cocoa touch APIs process strings in terms of UTF-16 code units. For example, instances of NSRange used with NSAttributedString and NSRegularExpression store substring offsets and lengths in terms of UTF-16 code units.

  • String.unicodeScalars is a collection of Unicode scalars. Use this API when you are performing low-level manipulation of character data.

  • String.characters is a collection of extended grapheme clusters, which are an approximation of user-perceived characters.

Note that when processing strings that contain human-readable text, character-by-character processing should be avoided to the largest extent possible. Use high-level locale-sensitive Unicode algorithms instead, for example, String.localizedStandardCompare(), String.localizedLowercaseString, String.localizedStandardRangeOfString() etc.

关于swift - 在 Swift 中获取字符串的第 n 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730193/

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