Objective C Char *,Const Char *,Cstring,CFString互转
一直傻傻分不清楚Char,Const Char,Cstring,CFString之间的转换关系,每次都要看之前写的东西才能想起来。
好记性不如烂笔头,决定把之前零散的东西再写出来汇整一起,下次不用再苦苦的翻东西找转换方式了。
-1. NSString转cstring
NSString *string1 = @"i am NSString";
NSLog(@"To cString : %s",[string1 UTF8String]);
-2. Const Char,Char转NSString
const char *cString = "i am const CString";
char *cString2 = "I am char";
NSLog(@"TO NSString1: %@",[NSString stringWithUTF8String:cString]);
NSLog(@"TO NSString2: %@",[NSString stringWithUTF8String:cString2]);
-3. Const Char 转Char
char* 表示一个指针变量,并且这个变量是可以被改变的。
const char*表示一个限定不会被改变的指针变量(意思是指针指向的内容不可变,但指针本身可以再赋值)
//方法一 strdup
//strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间
const char *cString = "i am const CString";
char *string2 = strdup(cString);
NSLog(@"To char1: %s",string2);
free(string2);
NSLog(@"To char2: %s",string2);
//方法二:强转const char
char *string3 = (char *)cString;
NSLog(@"To char3: %s",string3);
-4. Char 转Const Char
//强转
char *string4 = "I am Char";
const char *cString = string4;
NSLog(@"To const char:%s",cString);
-5. NSString 互转CFString
NSString *aNSString = @"NSString";
CFStringRef aCFString = (__bridge CFStringRef)aNSString;
NSString *bNSString = (__bridge NSString *)aCFString;
NSLog(@"the CFString : %@",aCFString);
NSLog(@"the NSString : %@",bNSString);
-6. Char 转CFString
char *cStringA = "cStringA";
CFStringRef bCFString =CFStringCreateWithCString(NULL, cStringA, kCFStringEncodingUTF8);
NSLog(@"the cfString : %@",bCFString);
-7. CFString转Char
第一种:利用CF 内置方法拿到String
//方法一 通过ssize_t
ssize_t s = CFStringGetMaximumSizeForEncoding(CFStringGetLength(bCFString), kCFStringEncodingUTF8);
char *d = malloc(s);
if(d) {
CFStringGetCString(bCFString, d, s, kCFStringEncodingUTF8);
printf("%s\n", d);
free(d);
}
//方法二 通过CFIndex
CFIndex length = CFStringGetLength(bCFString);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
char *buffer = (char *)malloc(maxSize);
if (CFStringGetCString(bCFString, buffer, maxSize,
kCFStringEncodingUTF8)) {
printf("%s\n", buffer);
}
第二种:利用前面的关系将CFstring转成NSString再转成char
NSString *testNS = (__bridge NSString *)bCFString;
char *testC =(char *) [testNS UTF8String];
NSLog(@"-->%s",testC);
Knowledge, like candlelight, can illuminate a person and countless people.