如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
Swift 1.2更新:不再有countElement来计算集合的大小。只需使用count函数作为替换:count(“Swift”)
Swift 2.0、3.0和3.1:
let strLength=字符串字符计数
Swift 4.2(4.0以后版本):[苹果文档-字符串]
let strLength=字符串计数
其他回答
截至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
我的两美分换雨燕3/4
如果需要有条件地编译
#if swift(>=4.0)
let len = text.count
#else
let len = text.characters.count
#endif
test1.endIndex给出的结果与Swift 3上的test1.characters.count相同
Swift 2.0版本:获取计数:yourString.text.characters.count
有趣的有用示例是在UITextView中显示某个数字(例如150)的字符倒计时:
func textViewDidChange(textView: UITextView) {
yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}
字符串和NSString是免费桥,因此您可以使用NSString和swift字符串的所有可用方法
let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count