如何计算字符串的长度?例如,我有一个定义如下的变量:

var test1: String = "Scott"

然而,我似乎找不到字符串的长度方法。


当前回答

您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。

“string”.length//6

免责声明:我写了这个扩展

其他回答

为Xcode 6 beta 4更新,更改方法utf16count-->utf16count

 var test1: String = "Scott"
 var length =  test1.utf16Count

Or

 var test1: String = "Scott"
 var length = test1.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)

Swift 5.0字符串可以被视为单个字符的数组。因此,要返回字符串的长度,可以使用string.count来计算字符数组中的项数。

自Swift 1.2起,utf16Count已删除。现在应该使用全局count()函数并传递字符串的UTF16视图。以下示例。。。

let string = "Some string"
count(string.utf16)

在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

Swift 2.0版本:获取计数:yourString.text.characters.count

有趣的有用示例是在UITextView中显示某个数字(例如150)的字符倒计时:

func textViewDidChange(textView: UITextView) {
    yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}