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
(1).将array数组转换为string字符串
NSString *str = [array componentsJoinedByString:@"#"];//#为分隔符
1
输入:[str,kkk,jjj]
输出:str#kkk#jjj
(2).将string字符串拆分为array数组[有分割符]
NSArray *array = [str componentsSeparatedByString:@"#"];//#为分隔符
1
输入: str#kkk#jjj
输出: [str,kkk,jjj]
——————————
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);
9、判断以**开头、结尾
//检查字符串是否以astring开头;
-(BOOL) hasPrefix:(NSString *) astring;
//检查字符串是否以astring结尾;
-(BOOL) hasSuffix:(NSString *) astring;
10、截取两段字符之间的字符串内容:
NSString *content_str = @"MM#********#***";
// 截取字符串方法(获取它们之间的字符串)
NSRange startRange = [copyString rangeOfString:@"MM#"];
NSRange endRange = [copyString rangeOfString:@"#"];
NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
content_str = [copyString substringWithRange:range];
11、判断一个字符是否是字母:
+(BOOL)JudgeString:(NSString *)string{
NSString *regex =@"[A-Za-z]+";
NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return[predicate evaluateWithObject:string];
}