如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
在Swift 4.1和Xcode 9.4.1中
在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性
例子:
//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)
//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);
其他回答
在Swift 4.1和Xcode 9.4.1中
在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性
例子:
//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)
//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);
Swift 1.2更新:不再有countElement来计算集合的大小。只需使用count函数作为替换:count(“Swift”)
Swift 2.0、3.0和3.1:
let strLength=字符串字符计数
Swift 4.2(4.0以后版本):[苹果文档-字符串]
let strLength=字符串计数
雨燕1.1
extension String {
var length: Int { return countElements(self) } //
}
雨燕1.2
extension String {
var length: Int { return count(self) } //
}
斯威夫特2.0
extension String {
var length: Int { return characters.count } //
}
雨燕4.2
extension String {
var length: Int { return self.count }
}
let str = "Hello"
let count = str.length // returns 5 (Int)
在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
苹果使它不同于其他主要语言。当前的方法是调用:
测试1字符计数
但是,要小心,当你说长度时,你指的是字符数而不是字节数,因为当你使用非ascii字符时,这两个字符可能不同。
例如"你好啊hi“.characters.count将为您提供5个字节,但这不是字节数。要获得真正的字节数,您需要执行“你好啊hi“.lengthOfBytes(使用:String.Encoding.utf8)。这将为您提供11。