swift 2.2中字符串的长度(逐字节)

时间:2016-08-09 06:16:59

标签: ios swift string-length

我们如何在Swift 2.2中找出字符串[declared String type, not NSString]的长度(逐字节)?

我知道一条出路就是使用_bridgeToObejectiveC().length

还有其他出路吗?

4 个答案:

答案 0 :(得分:2)

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

参考String length in Swift 1.2 and Swift 2.0Get the length of a String

答案 1 :(得分:1)

    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

答案 2 :(得分:1)

试试这段代码:

  

夫特

    let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let bytes : NSInteger =   test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
    NSLog("%i bytes", bytes);
  

目标C

参考此链接:

What is the length in bytes of a NSString?

答案 3 :(得分:1)

我认为类型转换是另一种更简单的方法来使用NSString类的方法属性。

print((str as NSString).length)