字符串创建

#import <Foundation/Foundation.h>

 

//c语言字符串

//helloworld

 

//1、c语言字符串必须是双引号包含

//2、c语言字符串中的每个字符占用一个字节空间

//3、c语言字符串的末尾有一个隐藏的\0字符

//4、打印c语言的字符还用%s占位符,传递字符串的首地址

 

//OC中的字符串对象

//NSString

//1、在字符串前面加上@符号

//2、打印字符串对象用%@

//3、OC字符串对象中的每一个字符都是unichar字符,unichar字符符合unicode编码

//4、UTF-8编码存储:这是多字节编码,不需要考虑字符的存储

 

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        char *cstring1 = "hello world";

        printf("%s\n",cstring1);

        

        //OCStr1是一个对象指针它指向常量区字符串对象

        NSString *OCStr1 = @"china 中国";//存储在常量区

        NSLog(@"OCStr1 = %@",OCStr1);

        

        //字符串对象的创建-构造方法

        //用c语言的字符串构造一个OC字符串对象

        NSString *OCStr2 = [[NSString alloc] initWithUTF8String:"welcome to china"];

        NSLog(@"OCStr2 = %@", OCStr2);

        

        //格式化构造OC字符串对象

        NSString *OCStr3 = [[NSString alloc] initWithFormat:@"%s##%d##%@","welcome", 888, @"hello"];

        NSLog(@"OCStr3 = %@", OCStr3);

        

        //用传递的字符串对象构造新的字符串对象

        NSString *OCStr = @"上海火车站";

        NSString *OCStr4 = [[NSString alloc] initWithString:OCStr];

        NSLog(@"OCStr4 = %@", OCStr4);

        

        //用c语言的字符串构造OC字符串对象

        NSString *OCStr5 = [[NSString alloc] initWithCString:"中国教育" encoding:NSUTF8StringEncoding];

        NSLog(@"OCStr5 = %@", OCStr5);

        

        //创建字符串对象---类方法

        //把c语言字符串转换成为OC字符串对象

        NSString *OCStr6 = [NSString stringWithUTF8String:"hello world"];

        NSLog(@"OCStr6 = %@", OCStr6);

        

        //用传入的字符串对象创建新的字符串对象

        NSString *OCStr7 = [NSString stringWithString:OCStr];

        NSLog(@"OCStr7 = %@", OCStr7);

        

        //格式化创建字符串对象

        NSString *OCStr8 = [NSString stringWithFormat:@"%d*%f*%s", 123, 89.43, "hello world"];

        NSLog(@"OCStr8 = %@", OCStr8);

        

        //用c语言字符串创造OC字符串对象

        NSString *OCStr9 = [NSString stringWithCString:"i am a good boy 中国" encoding:NSUTF8StringEncoding];

        NSLog(@"OCStr9 = %@", OCStr9);

        

        //字符串其他方法

        //求字符串对象的长度

        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;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值