user3569109
user3569109

Reputation: 191

Best way to get length of UTF-8 string in bytes?

I want to get a cString from NSString.
So we used c​String​Using​Encoding:​ method.
However, the return value of the c​String​Using​Encoding:​ method is not guaranteed.
(Apple's doc: The returned C string is guaranteed to be valid only until either the receiver is freed.)

So Apple recommends the get​CString:​max​Length:​encoding: method.
I want to pass the exact length to maxLength.

Example 1)

NSString *tmp = @"中日韓" // cString 9bytes
char *buffer = new tmp[9 + 1];
[tmp getCString:buffer maxLength:9+1 encoding:NSUTF8String​Encoding];

Example 2)

NSString *tmp = @"中日韓123" // cString 12bytes
char *buffer = new tmp[12 + 1];
[tmp getCString:buffer maxLength:12+1 encoding:NSUTF8String​Encoding];

Is there a way to know the lengths of 9 and 12 in the example above?

Upvotes: 1

Views: 1621

Answers (2)

rmaddy
rmaddy

Reputation: 318934

You can use cStringUsingEncoding to get the length. If you need the resulting char * to live longer than tmp, then simply copy the C-string:

NSString *tmp = @"中日韓" // cString 9bytes
const char *cStr = [tmp cStringUsingEncoding:NSUTF8StringEncoding];
size_t len = strlen(cStr);
char *buffer = new tmp[len + 1];
strcpy(buffer, cStr);

Upvotes: 3

Rob Napier
Rob Napier

Reputation: 299623

// Add one because this doesn't include the NULL
NSUInteger maxLength = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;

Upvotes: 5

Related Questions