iOS学习之字符串(NSString)的截取、匹配、分隔

截取

NSString *str1 = @"this is zero";

1.从第三个字符开始,截取长度为2的字符串.........注:空格算作一个字符
NSString *str2 = [str1 substringWithRange:NSMakeRange(5,2)];//str2 = "is"

2.截取从0位到第n为(第n位不算在内)
NSString *str3 = [str1 substringToIndex:4];//str3 = "this"

3.从第n为开始直到最后(包含第n位)
NSString *str4 = [str1 substringFromIndex:8];//str4 = "zero"

4.截取字符串的后4位
NSString *str5 = [str1 substringFromIndex:a.length-5];//str5 = "zero"........注:字符串的位数是在0位开始,所以截取后4位,应该是减5

匹配

NSString *string =@"sd是sfsfsAdfsdf";
NSRange range = [string rangeOfString:@"Ad"];//匹配得到的下标
NSLog(@"rang:%@",NSStringFromRange(range));  rang:{8, 2}
string = [string substringWithRange:range];//截取范围内的字符串
NSLog(@"截取的值为:%@",string);截取的值为:Ad

分隔

NSString *string =@"sdfsfsfsAdfsdf";
NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array); //结果是adfsfsfs和dfsdf

数组与字符串的转化(有分隔符)

string字符串转换为array数组
 NSArray  *array = [str componentsSeparatedByString:@","];--分隔符

将array数组转换为string字符串
 NSString *str = [array componentsJoinedByString:@","];--分隔符
posted @ 2019-08-29 14:18  brave-sailor  阅读(1300)  评论(0编辑  收藏  举报