如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
在swift4中,我一直使用string.count,直到今天我发现
string.endIndex.encodedOffset
是更好的替代方法,因为它更快-对于50000个字符,字符串大约比.count快6倍。.count取决于字符串长度,但.endIndex.encodedOffset不一样。
但有一个“不”。它对带有表情符号的字符串不好,它会给出错误的结果,所以只有count是正确的。
其他回答
您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。
“string”.length//6
免责声明:我写了这个扩展
这是我最后做的
let replacementTextAsDecimal = Double(string)
if string.characters.count > 0 &&
replacementTextAsDecimal == nil &&
replacementTextHasDecimalSeparator == nil {
return false
}
您可以将此函数添加到扩展
extension NSString {
func charLength() -> Int {
return count(self as String)
}
}
在Swift 4.2和Xcode 10.1中
在Swift中,字符串可以被视为单个字符的数组。所以字符串中的每个字符就像数组中的一个元素。要获取字符串的长度,请使用StringName.count属性。
在Swift中
yourStringName.character.count属性已弃用。所以直接使用strLength.count属性。
let strLength = "This is my string"
print(strLength.count)
//print(strLength.characters.count) //Error: 'characters' is deprecated: Please use String or Substring directly
如果目标C
NSString *myString = @"Hello World";
NSLog(@"%lu", [myString length]); // 11
test1.endIndex给出的结果与Swift 3上的test1.characters.count相同