iOS 截取字符串(持续更新)截取、匹配、分隔

截取:

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:str1.length - 4];//str5 = "zero"

5.去掉字符串的后4位
 NSString *str6 = [str1 substringToIndex:str1.length - 4];//str6 = "this is "

6. 去掉字符串的头4位
NSString *str7 = [str1 substringWithRange:NSMakeRange(4,str1.length - 4)];//str7 = " is zero"
 

 

匹配

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:@","];--分隔符

拼接

    NSString *str1 = @"kkk";
    NSString *str2 = @"ggg";
    NSString *strpingjie = [NSString stringWithFormat:@"@%@%",str1,str2];

 

posted on 2019-08-27 16:32  高彰  阅读(5314)  评论(0编辑  收藏  举报

导航