24

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

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
ticofab
  • 7,551
  • 13
  • 49
  • 90
  • How many actual bytes are taken **when** ? I hope you realize that the length in bytes depends on the encoding... – borrrden Jul 24 '14 at 04:16
  • Seems pretty clear the question is about how many bytes it takes when its sitting there in its internal representation in an NSString, which is UTF16, so the answer is it takes 2 bytes per character (for the most part -- there are some unicode chars that take more than 1 UTF16 codepoint to represent.). – Baxissimo Jan 16 '18 at 22:50

4 Answers4

55
NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);
Sanchit Paurush
  • 6,114
  • 17
  • 68
  • 107
  • 1
    This converts the string to UTF8 from it's internal representation of UTF16, so it does not tell you how much memory the NSString is actually using. – Baxissimo Jan 16 '18 at 22:47
9

To get the bytes use

NSData *bytes = [string dataUsingEncoding:NSUTF8StringEncoding];

Then you can check bytes.length

Number of bytes depend on the string encoding

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
6

You can try this:

NSString* string= @"myString";
NSData* data=[string dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger myLength = data.length;
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
3

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.

Baxissimo
  • 2,629
  • 2
  • 25
  • 23