如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
在Swift 2.x中,以下是如何找到字符串的长度
let findLength = "This is a string of text"
findLength.characters.count
返回24
其他回答
在Swift 4中:如果字符串不包含unicode字符,请使用以下命令
let str : String = "abcd"
let count = str.count // output 4
如果字符串包含unicode字符,请使用以下命令:
let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7
Swift 2.0版本:获取计数:yourString.text.characters.count
有趣的有用示例是在UITextView中显示某个数字(例如150)的字符倒计时:
func textViewDidChange(textView: UITextView) {
yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}
在Xcode 6.1.1中
extension String {
var length : Int { return self.utf16Count }
}
我认为脑力劳动者会在每一个次要版本上改变这一点。
test1.characters.count
将获取字符串中字母/数字等的数量。
ex:
test1 = "StackOverflow"
print(test1.characters.count)
(打印“13”)
自Swift 1.2起,utf16Count已删除。现在应该使用全局count()函数并传递字符串的UTF16视图。以下示例。。。
let string = "Some string"
count(string.utf16)