Reputation: 191
I want to get a cString from NSString.
So we used cStringUsingEncoding: method.
However, the return value of the cStringUsingEncoding: 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 getCString:maxLength: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:NSUTF8StringEncoding];
Example 2)
NSString *tmp = @"中日韓123" // cString 12bytes
char *buffer = new tmp[12 + 1];
[tmp getCString:buffer maxLength:12+1 encoding:NSUTF8StringEncoding];
Is there a way to know the lengths of 9 and 12 in the example above?
Upvotes: 1
Views: 1621
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
Reputation: 299623
// Add one because this doesn't include the NULL
NSUInteger maxLength = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
Upvotes: 5