字符串的操作
(1)创建字符串常量
NSString *str1=@"NSString1";
(2)用一个存在的字符串创建一个新的字符串对象
NSString *str2=@[NSString stringWithStringLstr1];
NSString *str22=[[NSString alloc] initWithString:str1];
(3)按照一定的格式拼接字符串
int age=20;int score=98;
NSString *str3=[NSString stringWithFormat:@"xiaoming'sage is %d score is %d",age,score];
(4)获取字符串长度
int l=[str3 length];/int l=str3.length;
(5)比较两个字符串是否相同
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 BOOL result=[str2 isEqualToString:str22]; 2 if(result==YES){ 3 NSLog(@"the same"); 4 } else { 5 NSLog(@"not the same"); 6 } 7 NSComparisonResult cmpResult=[@"abd" compare:@"abc"]; 8 if(cmpResult==NSOrderedAscending){ 9 NSLog(@"ascending"); 10 } else if(cmpResult==NSOrderedSame){ 11 NSLog(@"the same"); 12 } else { 13 NSLog(@"not the same"); 14 }
(6)获取字符串前缀后缀
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSString *httpStr=@"http://www.baidu.com"; 2 if([httpStr hasPrefix:@"http"]){ 3 NSLog(@"YES"); 4 } else { 5 NSLog(@"NO"); 6 } 7 if([httpStr hasSuffix:@".com"]){ 8 NSLog(@"YES"); 9 } else { 10 NSLog(@"NO"); 11 }
(7)截取字符串
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSString *sTemp1=@"hello world"; 2 NSLog(@"%@",[sTemp1 substringFromIndex:3]); //去掉开头长度为3的字符串 3 NSLog(@"%@",[sTemp1 substringToIndex:3]); //取开头长度为3的字符串 4 NSRange range = NSMakeRange(3,4); 5 NSLog(@"%@",[sTemp1 substringWithRange:range]); //从第三个字符开始截取长度为4的字符串 6 NSRange sRange=[sTemp1 rangeOfString:@"worl"]; //查询字符串sTemp1中是否包含“worl” 7 if(sRange.length !=0){ 8 NSLog(@"exist location:%lu",sRange.location); 9 } else { 10 NSLog(@"not exist"); 11 }
(8)字符串数字转换为对应的数据类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSString *numStr=@"123.12"; 2 int num=[numStr intValue]; //转换为int类型 3 double dou=[numStr doubleValue]; //转换为double类型
(9)字符串转换为数组
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSString *arrayStr=@"abc,bcd,cde,def"; 2 NSArray *array=[arrayStr componentsSeparatedByString:@","];
(10)可变字符的操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //创建可变字符串 2 NSMutableString *orgStr=[NSMutableString stringWithString:@"GuiZhou University of Finance and Economics"]; 3 //字符串替换 4 [orgStr replaceCharactersInRange:NSMakeRange(8,7) withString:@"guida"]; 5 NSLog(@"%@",orgStr); 6 //插入字符 7 [orgStr insertString:@" big" atIndex:7]; 8 NSLog(@"%@",orgStr); 9 //追加字符串 10 [orgStr appendString:@" OKK"]; 11 NSLog(@"%@",orgStr); 12 //重新设置字符串 13 [orgStr setString:@"xiaohuang"]; 14 NSLog(@"%@",orgStr); 15 //查找全部匹配字符并替换 16 NSRange orgStr1=[orgStr rangeOfString:@"a"]; 17 while(orgStr1.location!=NSNotFound){ 18 [orgStr replaceCharactersInRange:orgStr1 withStrig:@"P"]; 19 orgStr=[orgStr rangeOfString:@"a"]; 20 } 21 NSLog(@"%@",orgStr); 22 //删除一些字符 23 [orgStr deleteCharactersInRange:NSMakeRange(0,4)]; 24 NSLog(@"%@",orgStr);