当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 字符串对象的创建

字符串对象的创建

2018年03月31日  | 移动技术网IT编程  | 我要评论

长原结衣种子,琵琶鱼,四海图库彩色看图区

字符串必须用双引号包含 字符串中的每个字符占一个字节,ASCII C语言字符串的末尾有一个隐藏的’\0’ 打印C语言的字符串用 %s 占位符,传递字符串的首地址即可

OC字符串对象(NSString)

字符串前面加上 @ 打印OC的字符串对象用 %@ OC字符串中对象中的每一个字符都是uichar字符,uichar字符符合unicode编码 Utf8编码存储字符串,不需要考虑字符存储
#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        char *cstring = "Hello World 中国";
        printf("%c\n",cstring[7]);
        printf("%ld\n",sizeof("Hello World"));

        //ocstring是一个对象指针,指向常量区的字符串对象
        NSString *ocstring = @"Hello World 中国";//存储在常量区中
        NSLog(@"ocstring = %@",ocstring);

        //字符串的创建——构造方法
        //用C语言的字符串构造一个OC字符串对象
        NSString *OCStr = [[NSString alloc] initWithUTF8String:"Welcome to China"];
        NSLog(@"OCStr = %@",OCStr); //NSLog默认换行

        //格式化构造OC字符串对象
        NSString *OCStr1 = [[NSString alloc] initWithFormat:@"%s##%d##%@","Hello",888,@"China"];
        NSLog(@"OCStr1 = %@",OCStr1);

        //用传递的字符串对象构造新的字符串对象
        NSString *OCStr2 = @"上海火车站";
        NSString *OCStr3 = [[NSString alloc] initWithString:OCStr2];
        NSLog(@"OCStr3 = %@",OCStr3);

        //用C语言的字符串构造OC字符串对象,该方法主要用于iOS开发
        NSString *OCStr4 = [[NSString alloc] initWithCString:"中国教育" encoding:NSUTF8StringEncoding];
        NSLog(@"OCStr4 = %@",OCStr4);

        //创建字符串对象——类方法,将C语言字符串转换成OC字符串对象
        NSString *OCStr5 = [NSString stringWithUTF8String:"Hello World!"];
        NSLog(@"OCStr5 = %@",OCStr5);

        NSString *OCStr6 = [NSString stringWithString:OCStr2];
        NSLog(@"OCStr6 = %@",OCStr6);

        NSString *OCStr7 = [NSString stringWithFormat:@"%d,%.2f,%s",125,45.69,"Hello World"];
        NSLog(@"OCStr7 = %@",OCStr7);

        //用C语言的字符串来创建OC字符串对象
        NSString *OCStr8 = [NSString stringWithCString:"I am a good boy 来自中国" encoding:NSUTF8StringEncoding];
        NSLog(@"OCStr8 = %@",OCStr8);

        //字符串其它用法
        //求字符串的长度
        NSString *str = @"welcome 中国";
        NSInteger len = [str length];
        NSLog(@"len = %li",len);

        //获取指定下标位置的字符
        unichar ch = [str characterAtIndex:3];
        NSLog(@"ch = %C",ch); //%c 打印ASCII码字符,%C 打印unicode字符
    }
    return 0;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网