What is the length in bytes of a NSString?

后端 未结 4 1061
臣服心动
臣服心动 2021-02-05 06:03

How do I get the bytes length of NSString? if myString contains \"hallo\", myString.length will return 5, but how many actual bytes are ta

相关标签:
4条回答
  • 2021-02-05 06:32
    NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%i bytes", bytes);
    
    0 讨论(0)
  • 2021-02-05 06:33

    From the Apple documentation:

    An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0.

    So the memory used by an NSString is 2 bytes per character plus whatever fixed memory is used by the object itself.

    0 讨论(0)
  • 2021-02-05 06:35

    Well:

    NSString* string= @"myString";
    NSData* data=[string dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger myLength = data.length;
    
    0 讨论(0)
  • 2021-02-05 06:54

    To get the bytes use

    NSData *bytes = [string dataUsingEncoding:NSUTF8StringEncoding];
    

    Then you can check bytes.length

    Number of bytes depend on the string encoding

    0 讨论(0)
提交回复
热议问题