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

标签 swift string collections character subscript

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

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 或更高版本

Substring 类型是在 Swift 4 中引入的,用于生成子字符串 通过与原始字符串共享存储空间更快、更高效,因此这就是下标函数应该返回的内容。

试用一下 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]),但您应该只在以下情况下执行此操作 您打算保留子字符串。不然就更 有效地保持它为 Substring

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


为什么这不是内置的?

错误消息说“请参阅文档评论以进行讨论”。 Apple 在文件 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/24092884/

相关文章:

ios - 尝试设置 Firebase 推送通知时出现错误

python - 使用 Python 的字符串的子字符串

Python .format 在使用 psycopg2 时向字符串添加额外的引号

c# - IList 麻烦。固定尺寸?

java - 任何人都可以解释这个 HashMap 行为吗

ios - 如何在 Xcode 8.2 的 Playground 项目中使用 Swift 从用户那里获取输入?

ios - 在 View did load 方法中安排本地通知

ios - 键盘在桌面 View 交互上消除了很多错误

比较两个字符串中的单词

.net - 迭代 Queue<T> 是否保证按队列顺序?