简体   繁体   中英

How can I convert NSData to C string?

How can I convert [NSString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] result to C string?

Returns an NSData object containing a representation of the receiver encoded using a given encoding.

- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag

Note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator .

NSMutableData *data = [[@"foo" dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] mutableCopy];
char nul = '\0';
[data appendBytes:&nul length:sizeof(nul)];
const char *cString = [data bytes];

Or, simply:

const char *cString = [@"foo" UTF8String];

... with exactly the same result.

有一个-[NSString cStringUsingEncoding:]方法听起来很有希望。

It seems that you are asking the wrong question.

NSString* myString = @"Whatever";
const char* utf8String = [myString UTF8String];

Quite pointless to go through NSData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM