ticofab
ticofab

Reputation: 7717

What is the length in bytes of a NSString?

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?

Upvotes: 25

Views: 14974

Answers (4)

Rui Peres
Rui Peres

Reputation: 25927

You can try this:

NSString* string= @"myString";
NSData* data=[string dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger myLength = data.length;

Upvotes: 6

Baxissimo
Baxissimo

Reputation: 2619

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.

Upvotes: 3

Sanchit Paurush
Sanchit Paurush

Reputation: 6162

NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);

Upvotes: 56

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

To get the bytes use

NSData *bytes = [string dataUsingEncoding:NSUTF8StringEncoding];

Then you can check bytes.length

Number of bytes depend on the string encoding

Upvotes: 9

Related Questions