字符串的比较:
(1) isEqualToString
- (BOOL)isEqualToString:(NSString *)aString;
此方法的返回值是一个BOOL值(YES或NO)来表示字符串的内容是否相同.
使用方法:
实例1:
NSString *str1 = @"zhangsan 5";
NSString *str2 = [NSString stringWithFormat:@"hello %d",5];
NSLog(@"str2=%@",str2);
if ([str1 isEqualToString:str2]) {
NSLog(@"----");
}else{
NSLog(@"++++");
}
打印结果:
2017-06-26 23:09:35.317559+0800 test1[40109:15558436] str2=hello 5
2017-06-26 23:09:35.318508+0800 test1[40109:15558436] ++++
实例2:
NSString *str3 = @"lisi 5";
NSString *str4 = [NSString stringWithFormat:@"lisi %d",5];
//==运算符判断的是所指对象
if ([str3 isEqualToString:str4]) {
NSLog(@"----");
}else{
NSLog(@"++++");
}
//==运算符判断的是他们的指针数值
if (str3 == str4) {
NSLog(@"----");
}else{
NSLog(@"++++");
}
打印结果:
2017-06-26 23:20:47.248121+0800 test1[40147:15576454] ----
2017-06-26 23:20:47.249752+0800 test1[40147:15576454] ++++
(2)compare (注意:)不会区分大小写的比较
- (NSComparisonResult)compare:(NSString *)string;
实例1:
NSString *str3 = @"lisi";
NSString *str4 = @"LisI";
//==运算符判断的是所指对象
if ([str3 compare:str4]) {
NSLog(@"相同");
}else{
NSLog(@"不相同");
}
打印结果:
2017-06-26 23:25:31.351703+0800 test1[40175:15584618] 相同
(3)字符串的截取
实例1:
NSString*str =@"woaipingguo";
str = [str substringToIndex:7];//截取掉下标7之后的字符串
NSLog(@"第一次截取的值为:%@",str);
NSString*str1 =@"abcdefgh";
NSString *str2= [str1 substringFromIndex:4];//截取掉下标4之前的字符串(去掉)
NSLog(@"第二次截取的值为:%@",str2);
NSString *str3=[str1 substringWithRange:NSMakeRange(0, 3)];//截取范围里的字符串
NSLog(@"第三次截取的值为:%@",str3);
打印结果:
2017-06-26 23:46:47.330874+0800 test1[40325:15619258] 第一次截取的值为:woaipin
2017-06-26 23:46:47.331945+0800 test1[40325:15619258] 第二次截取的值为:efgh
2017-06-26 23:46:47.331982+0800 test1[40325:15619258] 第三次截取的值为:abc
(4)从字符A中分隔成2个元素的数组
实例1:
NSString*string =@"sdfsfsfsAdfsdf";
NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array);
打印结果:
2017-06-26 23:48:58.236463+0800 test1[40340:15622916] array:(
sdfsfsfs,
dfsdf
)