swift 2.2 中字符串的长度(按字节计算)
length (byte-wise) of a string in swift 2.2
我们如何在 Swift 2.2 中找出字符串 [declared String type, not NSString]
的长度(按字节计算)?
我知道一种解决方法是使用 _bridgeToObejectiveC().length
还有别的出路吗?
let str: String = "Hello, World"
print(str.characters.count) // 12
let str1: String = "Hello, World"
print(str1.endIndex) // 12
let str2 = "Hello, World"
NSString(string: str2).length //12
参考 and Get the length of a String
let str: String = "Hello, World"
print(str.characters.count) // 12
let byteLength = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength)")//12
let str2: String = "你好"
print(str2.characters.count) // 2
let byteLength2 = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength2)")//12
试试这个代码:
Swift
let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let bytes : NSInteger = test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
NSLog("%i bytes", bytes);
Objective C
参考这个 link:
What is the length in bytes of a NSString?
我认为类型转换是使用 NSString 的方法和属性的另一种更简单的方法 class。
print((str as NSString).length)
我们如何在 Swift 2.2 中找出字符串 [declared String type, not NSString]
的长度(按字节计算)?
我知道一种解决方法是使用 _bridgeToObejectiveC().length
还有别的出路吗?
let str: String = "Hello, World"
print(str.characters.count) // 12
let str1: String = "Hello, World"
print(str1.endIndex) // 12
let str2 = "Hello, World"
NSString(string: str2).length //12
参考
let str: String = "Hello, World"
print(str.characters.count) // 12
let byteLength = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength)")//12
let str2: String = "你好"
print(str2.characters.count) // 2
let byteLength2 = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength2)")//12
试试这个代码:
Swift
let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let bytes : NSInteger = test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
NSLog("%i bytes", bytes);
Objective C
参考这个 link:
What is the length in bytes of a NSString?
我认为类型转换是使用 NSString 的方法和属性的另一种更简单的方法 class。
print((str as NSString).length)