如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
您可以使用str.utf8.count和str.utf16.count,我认为这是最好的解决方案
其他回答
test1.endIndex给出的结果与Swift 3上的test1.characters.count相同
字符串和NSString是免费桥,因此您可以使用NSString和swift字符串的所有可用方法
let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count
在Swift 4.1和Xcode 9.4.1中
在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性
例子:
//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)
//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);
在Swift 2.0中,计数不再有效。您可以改用此选项:
var testString = "Scott"
var length = testString.characters.count
这是我最后做的
let replacementTextAsDecimal = Double(string)
if string.characters.count > 0 &&
replacementTextAsDecimal == nil &&
replacementTextHasDecimalSeparator == nil {
return false
}