Apple开发_OC字符串与C语言字符串之间的相互转换

1、C转OC字符串

const char *cString = "This is a C string";

// 动态方法
NSString *ocString1 = [[NSString alloc] initWithUTF8String:cString];
NSString *ocString2 = [[NSString alloc] initWithCString:cString encoding:NSUTF8StringEncoding];
NSString *ocString3 = [[NSString alloc] initWithFormat:@"%s", cString];


// 静态方法
NSString *ocString4 = [NSString stringWithCString:cString encoding:NSUTF8StringEncoding];
NSString *ocString5 = [NSString stringWithUTF8String:cString];
NSString *ocString6 = [NSString stringWithFormat:@"%s", cString];

NSLog(@"\n——%@\n——%@\n——%@\n——%@\n——%@\n——%@",ocString1,ocString2,ocString3,ocString4,ocString5,ocString6);

2、OC转C字符串

// 只有静态方法
NSString *ocString = @"This is a OC string";

const char *cString1 = [ocString cStringUsingEncoding:NSUTF8StringEncoding];
const char *cString2 = [ocString UTF8String];

NSLog(@"\n——%s\n——%s",cString1,cString2);
posted @ 2018-12-21 21:45  CH520  阅读(320)  评论(0编辑  收藏  举报