我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
当前回答
如果你看到不能下标一个类型为'String'的值…使用这个扩展:
斯威夫特3
extension String {
subscript (i: Int) -> Character {
return self[self.characters.index(self.startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return self[start..<end]
}
subscript (r: ClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return self[start...end]
}
}
斯威夫特2.3
extension String {
subscript(integerIndex: Int) -> Character {
let index = advance(startIndex, integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = advance(startIndex, integerRange.startIndex)
let end = advance(startIndex, integerRange.endIndex)
let range = start..<end
return self[range]
}
}
来源:http://oleb.net/blog/2014/07/swift-strings/
其他回答
注意:请参阅Leo Dabus关于正确实现Swift 4和Swift 5的回答。
Swift 4或更高版本
Substring类型是在Swift 4中引入的,用于生成子字符串 通过与原始字符串共享存储,更快更有效,这就是下标函数应该返回的。
在这里试试吧
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)] }
}
要将子字符串转换为字符串,您可以简单地 做字符串(字符串[0..2]),但你应该只做如果 您计划保留子字符串。否则,就更多了 有效地保持它为Substring。
It would be great if someone could figure out a good way to merge these two extensions into one. I tried extending StringProtocol without success, because the index method does not exist there. Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementation
为什么这不是内置的?
错误消息显示“请参阅文档注释以进行讨论”。Apple在文件unavailablestringapi .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.
使用字符就可以了。您可以快速地将字符串转换为字符数组,可以由CharacterView方法操作。
例子:
let myString = "Hello World!"
let myChars = myString.characters
(完整的CharacterView文档)
(在Swift 3中测试)
斯威夫特4
String(Array(stringToIndex)[index])
这可能是一次性解决这个问题的最好方法。您可能希望首先将String转换为数组,然后再将结果转换为String。否则,将返回字符而不是字符串。
示例String(Array("HelloThere")[1])将返回"e"作为字符串。
(数组("HelloThere")[1]将返回"e"作为字符。
Swift不允许字符串像数组一样被索引,但这就完成了工作,用蛮力的方式。
你可以使用SwiftString (https://github.com/amayne/SwiftString)来做这件事。
"Hello, world!"[0] // H
"Hello, world!"[0...4] // Hello
免责声明:我写了这个扩展
Swift的String类型没有提供characterAtIndex方法,因为Unicode字符串有几种编码方式。你要用UTF8, UTF16,还是别的?
您可以通过检索String来访问CodeUnit集合。utf8和String。utf16属性。您还可以通过检索String来访问UnicodeScalar集合。unicodeScalars财产。
在NSString实现的精神中,我返回一个unichar类型。
extension String
{
func characterAtIndex(index:Int) -> unichar
{
return self.utf16[index]
}
// Allows us to use String[index] notation
subscript(index:Int) -> unichar
{
return characterAtIndex(index)
}
}
let text = "Hello Swift!"
let firstChar = text[0]