本帖最后由 S970028126 于 2015-6-26 23:15 编辑
NSString :
NSString *str = @"hello world!";
NSString *str2 = [[NSString alloc] initWithString: str];
NSString *str3 = [[NSString alloc] initWithUTF85String: "hello world!"]; //用c的字符串创建OC的字符串对象
NSString *str4 = [[NSString alloc] initWithFormat: @"hello %d %c", 5, 'A']; //使用格式符,拼接一个字符串
NSLog(@"%@", str);
后面三个通过alloc产生,必须通过release释放
创建临时字符串(自动释放):
NSString *str5 = [NSString stringWithUTF8String: "hello world!"];
NSString *str6 = [[NSString stringWithFormat: @"%d %@ %c", 1, @"hello world", 'R']];
NSString *str7 = [NSString stringWithString: str];
字符串自带很多方法
判断两个字符串是否相等:
BOOL ret = [str isEqualToString: str2];
NSLog(@"%d", ret); //输出为0,两个字符串不相等
判断两个字符串谁大谁小
NSComparisonResult ret = [str compare:str2];
if (ret == NSOrderedAscending)
{
NSLog(@"str < str2");
}
else if (ret == NSOrderedSame)
{
NSLog(@"str == str2");
}
else if (ret == NSOrderedDescending)
{
NSLog(@"str > str2");
}
显示字串在字符串中的位置
NSString * str = @"I am a so good man";
NSString *subStr = @"so";
NSRange range = [str rangeOfString: subStr];
NSlog(@"location:%lu length:%lu", range,location, range.length);
从字符串中提取新字符串生成新字符串,返回字符串地址
NSString *str = @"09081903";
NSString *str2 = [str substringToIndex:6];
//从str中提取从头至第6个字符串(不包括第6个,从0到5),生成新字符串,并返回字符串地址,开区间
生成一个新字符串,原字符串不变
NSString *str3 = [str substringFromIndex:6];
//从str中提取第6个字符(包括第6个),到最后一个字符,生成新字符串,返回字符串地址,闭区间
NSRange range = {3, 4};
NSString *str = [str substringWithRange: range];
//从第3个开始,提取4个
可以用NSMakeRange(3,4)
NSString *str = [str substringWithRange: NSMakeRange(3,4)];
字符串的一个子类:
可变字符串 :字符串
NSMutableString:增删改查
NSMutableString *Str = [[NSMutableString alloc] init];
[str setString: @"hello"];
增:
追加:append
[str appendString: @"123"];
[str appendFormat: @"%c",'D'];
插入:insert
[str insertString: @"XXXX" atIndex:4];(从0开始数)
[str insertString: [NSString stringWithFormat: @"%d", -54] atIndex:7];
//插入特殊字符,可以通过创建一个临时字符串的方法
删:delete
[str deleteCharactersInRange: NSMakeRange(3,5)];
改:replace
[str replaceCharactersInRange:NSMakeRange(3,2) withString: @"RRRRRRRRRR"];
替换字符串的长度可以不一样
|
|