iOS中 OC字符串 与 C语言字符串 相互转换

一、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];

 

 

二、OC字符串转C字符串

NSString *ocString = @"This is a OC string";
    //类方法
    const char *cString1 = [ocString cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cString2 = [ocString UTF8String];

 

爱编程-编程爱好者经验分享平台

文章评论

  

版权所有 爱编程 © Copyright 2012. w2bc.com. All Rights Reserved.
闽ICP备12017094号-3