今天学习的NSString用法记录下,顺便发个帖子。
- //创建常量字符串
- NSString* str=@"This is a string";
-
- //1.获取字符串的长度</span>
- NSUInteger len=[str length];
- NSLog(@"length=%lu", len); //result:16
-
- //2.获取下标为1的字符,用unichar接收
- unichar c=[str characterAtIndex:1];
- NSLog(@"%c", c); //result:h
- NSLog(@"%lu", sizeof(unichar)); //result:2
-
- //3.initWithString初始化字符串</span>
- str=[[NSString alloc]
- initWithString@"Hello World"];
- NSLog(@"%@", str); //result:hello world
- //4.用标准c字符串创建oc字符串 :initWithCString 方法
- str=[[NSString alloc]
- initWithUTF8String:"This is c string"];
- NSLog(@"%@", str); //result:This is c string
- printf("%s\n", [str UTF8String]);
- str=[NSString stringWithString:@"Hello iOS"];
- NSLog(@"%@", str); //result Hello iOS
-
- int age=30;
- //5.创建格式化字符串。
- str=[[NSString alloc]
- initWithFormat:@"age=%d", age];
- NSLog(@"%@", str);
-
复制代码
|
|