如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
在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 1.2起,utf16Count已删除。现在应该使用全局count()函数并传递字符串的UTF16视图。以下示例。。。
let string = "Some string"
count(string.utf16)
斯威夫特4
let str = "Your name"
str.count
记住:空格也计入数字
截至Swift 4+
只是:
test1.count
出于原因。
(感谢Martin R)
截至Swift 2:
在Swift 2中,苹果将全局函数改为协议扩展,即与任何符合协议的类型相匹配的扩展。因此,新语法为:
test1.characters.count
(感谢JohnDule的提醒)
截至Swift 1
使用计数字符方法:
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
从Apple Swift指南
(注意,对于1.2之前的Swift版本,这将是countElements(unusualMenagerie))
对于变量
length = count(test1) // was countElements in earlier versions of Swift
或者可以使用test1.utf16count
您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。
“string”.length//6
免责声明:我写了这个扩展
这是我最后做的
let replacementTextAsDecimal = Double(string)
if string.characters.count > 0 &&
replacementTextAsDecimal == nil &&
replacementTextHasDecimalSeparator == nil {
return false
}