在Swift编程语言中获取字符串的第n个字符 [英] Get nth character of a string in Swift programming language

查看:556
本文介绍了在Swift编程语言中获取字符串的第n个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取字符串的第n个字符?我试过没有运气的方括号( [] )访问器。

How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = "Hello, world!"

var firstChar = string[0] // Throws error




错误:下标不可用:无法对带Int的字符串进行下标,请参见文档注释以进行讨论

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


推荐答案

注意:请参阅 Leo Dabus的答案 Swift 4和Swift 5的正确实现。

Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5.

Swift 4中引入了Substring 类型,通过与原始字符串共享存储来使子字符串
更快,更高效,因此下标函数应该返回该子字符串。

The Substring type was introduced in Swift 4 to make substrings faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return.

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)] }
}

要将子字符串转换为 String ,只需
String(string [0..2]),但是只有在
打算保留子字符串的情况下,才应该这样做。否则,将其保留为子字符串的效率更高

To convert the Substring into a String, you can simply do String(string[0..2]), but you should only do that if you plan to keep the substring around. Otherwise, it's more efficient to keep it a Substring.

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

错误消息为 请参阅文档注释以进行讨论 。 Apple在文件 UnavailableStringAPIs.swift

The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift:


带整数的字符串不可用。

Subscripting strings with integers is not available.

字符串中第 i 个字符的概念在不同的库和系统
组件中具有
个不同的解释。应该根据用例和所涉及的API选择正确的解释
,因此 String
不能用整数下标。

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提供了几种不同的方法来访问存储在字符串中的字符
数据。

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


  • String.utf8
    字符串中UTF-8代码单元的集合。将字符串转换为UTF-8时,请使用此API。
    大多数POSIX API按照UTF-8代码单位处理字符串。

  • 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
字符串中的UTF-16代码单元的集合。大多数Cocoa和Cocoa touch API以
的UTF-16代码单位来处理字符串。例如,
NSRange 的实例与 NSAttributedString
一起使用NSRegularExpression
的UTF-16代码单位存储子字符串偏移量和长度。

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 是Unicode标量的集合。
在执行字符数据的
的低级处理时使用此API。

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

String.characters 是扩展的字素
簇的集合,这些簇是用户感知的
字符的近似值。

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

请注意,在处理包含人类可读文本的字符串时,应尽可能避免
逐字符处理。而是使用高级的区域设置敏感的Unicode算法,例如
String.localizedStandardCompare()
String.localizedLowercaseString
String.localizedStandardRangeOfString()等。

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编程语言中获取字符串的第n个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆