本文主要是介绍NSString处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
NSString *first = @"abdcbabcdbabcbacbcb";NSString *second = @"cdcdcdcd";NSString *third = @"string1:string2:string3:string4";NSArray *strings = [NSArray arrayWithObjects:first, second, third, nil];// 将字符串数组连接起来NSString *string1 = [strings componentsJoinedByString:@"@"];NSLog(@"%@", string1);/*abdcbabcdbabcbacbcb@cdcdcdcd@string1:string2:string3:string4*/NSString *string2 = [strings componentsJoinedByString:@""];NSLog(@"%@", string2);/*abdcbabcdbabcbacbcbcdcdcdcdstring1:string2:string3:string4*/// 将字符串根据特定字符分割成字符串数组NSArray *chunks1 = [string1 componentsSeparatedByString:@"@"];NSLog(@"%@", chunks1);/*(abdcbabcdbabcbacbcb,cdcdcdcd,"string1:string2:string3:string4")*/NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"bc"];NSArray *chunks2 = [first componentsSeparatedByCharactersInSet:charSet];NSLog(@"%@", chunks2);/*(a,d,"",a,"",d,a,"","",a,"","","","")*/// 字符串替换(NSMutableString)NSMutableString *mstring = [NSMutableString stringWithString:third];NSRange range = NSMakeRange(0, 5);[mstring replaceOccurrencesOfString:@"s" withString:@"A" options:NSLiteralSearch range:NSMakeRange(0, third.length)];NSLog(@"%@", mstring);/*Atring1:Atring2:Atring3:Atring4*/[mstring replaceCharactersInRange:range withString:@"BBBBBBBBBBBBBBB"];NSLog(@"%@", mstring);/*BBBBBBBBBBBBBBBg1:Atring2:Atring3:Atring4*/// 获取子字符串NSRange range2 = NSMakeRange(0, 4);NSString *string3 = [mstring substringWithRange:range2];NSLog(@"%@", string3);/*BBBB*/NSString *string4 = [mstring substringFromIndex:10];NSLog(@"%@", string4);/*BBBBBg1:Atring2:Atring3:Atring4*/NSString *string5 = [mstring substringToIndex:5];NSLog(@"%@", string5);/*BBBBB*/// 去掉字符串中的'\n' '\t' ' 'NSString *tn = @"\t \nha ha\n\t";NSString *trimedStr1 = [tn stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];NSLog(@"%@", trimedStr1);/*ha ha*/NSString *trimedStr2 = [tn stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];NSLog(@"%@", trimedStr2);/*ha ha*/// 对于多行的字符串,可以按行处理该字符串NSMutableArray *altitudes = [NSMutableArray array];NSString *altitudeString = @"a\nb\nc\nd\n";[altitudeString enumerateLinesUsingBlock: ^(NSString *line, BOOL *stop) {[altitudes addObject: line];}];NSLog(@"%@", altitudes);
这篇关于NSString处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!