[NSString lengthOfBytesUsingEncoding]
Returns the number of bytes required to store the receiver in a given encoding.
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
Parameters
- enc
- The encoding for which to determine the receiver's length.
Return Value of [NSString lengthOfBytesUsingEncoding]
The number of bytes required to store the receiver in the encoding enc in a non-external representation. The length does not include space for a terminating
NULL
character. Returns 0
if the specified encoding cannot be used to convert the receiver or if the amount of memory required for storing the results of the encoding conversion would exceed NSIntegerMax
.Discussion
The result is exact and is returned in
O(n)
time.
Example of [NSString lengthOfBytesUsingEncoding]
NSUInteger numberOfBytes = [message lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
void *buffer = malloc(numberOfBytes);
NSUInteger usedLength = 0;
NSRange range = NSMakeRange(0, [message length]);
BOOL result = [message getBytes:buffer maxLength:numberOfBytes usedLength:&usedLength encoding:NSUnicodeStringEncoding options:0 range:range remainingRange:NULL];
...
free(buffer);
Example of [NSString lengthOfBytesUsingEncoding]
NSString *myAccentStr = @"José";
NSUInteger l1 = [myAccentStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSUInteger l2 = [myAccentStr lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
NSUInteger l3 = [myAccentStr lengthOfBytesUsingEncoding:NSUTF32StringEncoding];
NSLog(@"%ld %ld %ld", (long)l1, (long)l2, (long)l3);
> 5, 8, 16
Example of [NSString lengthOfBytesUsingEncoding]
NSUInteger arbLength = [englishArabicMixText lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
char strArb [arbLength];
[englishArabicMixText getCString:strArb maxLength:arbLength encoding:NSUTF8StringEncoding];