NSString*str =
@"aaaaaaaaa bbbbbbbbb ccccccccccccccccccc"
@"sdafasdfwerwlkjsaldkfjklkdjs934523jklad"
@"as0932i4oriewjko201384209u42l3jasf fi0";
1.查找
NSRange range = [str rangeOfString:@"567"];
if (range.location == NSNotFound)
{
NSLog(@"str中没有找到567");
}else {
NSLog(@"搜索范围%@",NSStringFromRange(range));
}
或者是:
if (range.length == 0 ) {
NSLog(@"str中没有找到567");
}
NSLiteralSearch区分大小写(完全比较)
NSCaseInsensitiveSearch不区分大小写
NSNumericSearch只比较字符串的个数,而不比较字符串的字面值
从尾开始搜索:
range = [str rangeOfString:@"456" options:NSBackwardsSearch] ;
NSLog(@"从尾搜索的范围%@",NSStringFromRange(range));
下面的方法在ios8.0以后使用,也是判断是否包含某个字符串:
BOOL result = [@“123" containsString:@"2"];
2.截取
NSString*bStr = [str substringWithRange:NSMakeRange(loc,2)];
loc表示从第几个字符开始,2表示截取两个字符;
从首字符开始截取n个字符:
[str substringToIndex:n];
从第n+1位开始截取,至字符串最后:
[str substringFromIndex:n];
3.拆分
NSString*string =@"11111111A22222222";
NSArray*array = [string componentsSeparatedByString:@"A"];//从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array);
NSLog(@"array1 ==== %@",[array firstObject]);
NSLog(@"array2 ==== %@",[array lastObject]);
打印结果是:
array:(
11111111,
22222222
)
array1 ==== 11111111
array2 ==== 22222222
4.替换
NSString*str =@"12345678";
NSString*replacedStr = [str stringByReplacingOccurrencesOfString:@"345"withString:@"想要替换成的字符串"];
NSLog(@"replacedStr ==== %@", replacedStr);
打印结果:
replacedStr ==== 12想要替换成的字符串678
5.验证
NSString*str1 =@"http:www.baidu.com";
BOOL a = [str1 hasPrefix:@"http"];//是否是以http开头
BOOL b = [str1 hasSuffix:@"com"];//文件路径是否以com结尾
NSLog(@"a ===== %d ,b ==== %d",a,b);
打印结果:
a ===== 1 ,b ==== 1
6.转成数字
[str boolValue];
[str integerValue];
7.改变字符串的大小写
NSString* str2 =@"beiJING";
NSString*da = [str2 uppercaseString];//转成大写
NSString*xiao = [str2 lowercaseString];//转成小写
NSString*shouDa = [str2 capitalizedString];//首字母大写,其余小写
NSLog(@"\n大写==%@\n小写=== %@\n首字母大写其余小写=== %@",da,xiao,shouDa);
打印结果:
大写==BEIJING
小写=== beijing
首字母大写其余小写=== Beijing
8.编码,解码
编码:
NSString*hStr =@"你好啊";
NSString*hString = [hStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"hString === %@",hString);
解码:
NSString*str3 =@"\u5982\u4f55\u8054\u7cfb\u5ba2\u670d\u4eba\u5458\uff1f";
NSString*str5 = [str3stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"string ==== %@",str5);
打印结果:
hString === %E4%BD%A0%E5%A5%BD%E5%95%8A
string ====如何联系客服人员?