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

var test1: String = "Scott"

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


当前回答

test1.characters.count

将获取字符串中字母/数字等的数量。

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(打印“13”)

其他回答

在Swift 2.0中,计数不再有效。您可以改用此选项:

var testString = "Scott"
var length = testString.characters.count

在Swift 2.x中,以下是如何找到字符串的长度

let findLength = "This is a string of text"
findLength.characters.count

返回24

字符串和NSString是免费桥,因此您可以使用NSString和swift字符串的所有可用方法

let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count

在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
var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

这将统计正则Swift字符串中的字符

countElements((newString as String))    

这将统计NSString中的字符