OC字串與C語言字串之間的相互轉換
阿新 • • 發佈:2018-12-21
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);