字符串
- NSString类属于Foundation框架中字符串操作类
Foundation框架是iOS开发编程的基础框架,其中包括集合、字典、时间,日期等。 - NSString由unichar字符组成, Unichar字符是以Unicode(至少2个字节)多字节字符为标准构成.
NSString和NSMutableString
区别
- NSString创建赋值后不能动态修改长度和内容,除非给重新赋值。
- NSMutableString类似与链表的,可以进行修改长度,插入,删除等操作
- NSMutableString继承于 NSString
创建和初始化
常量字符串
NSString *string =@“字符串";
NSLog(@"address:%p ,%@", string, [string class]);
2016-06-15 14:49:50.891 OC_Assignment_3_1[1954:1279483] address=0x100001040,__NSCFConstantString,Hello world!
__NSCFConstantString
是常量串,不可以修改,在内存静态存储区存储
可变字符串
NSMutableString* cpyStr = [str mutableCopy];
NSLog(@"cpyStr=%@,address=%p,%@", cpyStr, cpyStr,[cpyStr class]);
2016-06-15 14:55:09.659 OC_Assignment_3_1[1978:1308744] cpyStr=Hello world!,address=0x1007001e0,__NSCFString
__NSCFString
是可变串,可以修改,在内存堆区存储
字符串操作函数
NSString
NSString* str=@“Hello world!”;
获取字符串长度
NSLog(@"%ld",[str length]);
获取子字符串
NSString * ptr1 = [str substringToIndex:4];
NSString * ptr2 = [str substringFromIndex:3];
2016-06-15 15:13:51.073 NSString[2040:1377297] Hell
2016-06-15 15:13:51.073 NSString[2040:1377297] lo world!
判断字符串是否以指定字符串开头
NSString* string = @"www.zihin.com";
BOOL ret = [string hasPrefix:@"www"];
判断字符串是否以指定的字符串结尾
NSString * string2 = @"zihin.txt";
BOOL ret1 = [string2 hasSuffix:@".txt"];
判断字符串是否相等
BOOL result = [string1 isEqualToString:string2];
比较字符串大小
BOOL result = [string1 compare:string2];
字符串分割
NSString* string = @"A, B, C, D";
NSArray* array = [string componentsSeparatedByString:@","];
NSMutableString
NSString操作函数 NSMutableString都能使用
可变字符串—增加,删除,修改
- (void)insertString:(NSString *)aStringatIndex:(NSUInteger)loc;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)appendString:(NSString *)aString;
OC字符串与C的字符串转化
C的字符串转化为OC的字符串
NSString* str = [[NSString alloc]initWithUTF8String: "hello"];
OC字符串转化为C的字符串
NSString * str = @"hello";
const char *p = [str UTF8String];
数字转化
NSString* str = @"123";
将数字串转化成整型数据
int a = [str intValue];
将数字串转化成float型
float b = [str floatValue];
将数字串转化成double型
double c = [str doubleValue];
网友评论