iOS字符串截取、包含、替换

1.截取两个指定字符串中的字符串

NSString *string = @"abavavasdsvx,as.dsf/,.[abcdefghijklmn]dgdfg";

NSRange start = [string rangeOfString:@"["];

NSRange end = [string rangeOfString:@"]"];

NSString *sub = [string substringWithRange:NSMakeRange(start.location, end.location-start.location+1)];

NSLog(@"sub=%@",sub);

控制台就输出:[abcdefghijklmn]

2.字符串截取到第n位  (substringToIndex: n)(第n 位不算再内)

- (void)viewDidLoad

{

NSString  *a = @"i like long dress";

NSString *b = [a substringToIndex:4];

NSLog(@"\n b: %@",b);

控制台输出: b: i li

3.字符串从第n 位开端截取,直到最后 (substringFromIndex:n)(包含第 n 位)

- (void)viewDidLoad

{

NSString  *a = @"i like long dress";

NSString *b = [a substringFromIndex:4];

NSLog(@"\n b: %@",b);

}

控制台输出: b: ke long dress

}

4.根据下标截取字符串

NSString*string =@"sdfsfsfsAdfsdf";

string = [string substringToIndex:7];//截取掉下标7之后的字符串

NSLog(@"截取的值为:%@",string);

[string substringFromIndex:2];//截取掉下标2之前的字符串

NSLog(@"截取的值为:%@",string);

5.匹配字符串

NSString*string =@"sdfsfsfsAdfsdf";

NSRangerange = [stringrangeOfString:@"f"];//匹配得到的下标

NSLog(@"rang:%@",NSStringFromRange(range));

string = [string substringWithRange:range];//截取范围类的字符串

NSLog(@"截取的值为:%@",string);

6.分隔字符串

NSString*string =@"sdfsfsfsAdfsdf";

NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组

NSLog(@"array:%@",array); //结果是adfsfsfs和dfsdf

7、替换字符串

例如:将字符串中所有带有“-”的字符,都替换成“→”,然后将其更改颜色

NSString *pointStr = @"→";

NSString *trafficStr = @"要我知道-你还得-等放假恩发-第三方的-的发热及";

NSString *strUrl = [trafficStr stringByReplacingOccurrencesOfString:@"-" withString:pointStr];                   //这里就是替换字符串

NSArray *trafficArr = [trafficStr componentsSeparatedByString:@"-"];   //这里是通过将字符串中“-”拆分成一个数组里

NSMutableAttributedString *strP = [[NSMutableAttributedString alloc]initWithString:strUrl];

NSInteger rangeMin = 0;

int i = 0;

NSMutableArray *tempArr = trafficArr.mutableCopy;

[tempArr removeLastObject];

for (NSString *tempstr in tempArr) {

NSInteger tempStrLenth = tempstr.length;

rangeMin += tempStrLenth;

NSRange range = {rangeMin+i,1};     // 这里是遍历拆分好的数组中每一个字符串,从而得知要替换的“-”的下标位置

NSLog(@"range%lu , %d",(unsigned long)range.location, i);

[strP addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#23beae"] range:range];

[strP addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];

i++;

cell.traffic.attributedText = strP;

}

你可能感兴趣的:(iOS字符串截取、包含、替换)