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

var test1: String = "Scott"

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


当前回答

这里有一些比使用全局函数更短、更自然的方法:

aString.utf16count

我不知道它是否在beta 1中可用。但它肯定在beta 2中。

其他回答

这是我最后做的

let replacementTextAsDecimal = Double(string)

if string.characters.count > 0 &&
    replacementTextAsDecimal == nil &&
    replacementTextHasDecimalSeparator == nil {
        return false
}
test1.characters.count

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

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(打印“13”)

从文本视图或文本字段获取字符串值:

let textlengthstring = (yourtextview?.text)! as String

查找字符串中的字符数:

let numberOfChars = textlength.characters.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

现在(在Swift 2.3中),如果您使用:

myString.characters.count 

该方法将返回“Distance”类型,如果您需要该方法返回Integer,则应按如下方式键入cast:

var count = myString.characters.count as Int