1.字符串比较方法compare: option
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *str1=@"abc";
- NSString *str2=@"acd";
- //options常见3个位枚举:
- //NSCaseInsensitiveSearch:不区分大小写.
- //NSLiteralSearch:进行完全比较,区分大小写(默认).
- //NSNumericSearch:比较字符串的字符个数,而不是字符值.
- //options中可以在条件中加上'|',表示多个条件
- NSComparisonResult result=[str1 compare:str2 options:NSCaseInsensitiveSearch];
- //compare的返回值有3种类型:
- //1.NSOrderedAscending 升序:str1<str2 返回值-1;
- //2.NSOrderedSame str1==str2 返回值0;
- //3.NSOrderedDescending 降序:str1>str2 返回值1;
- switch (result) {
- case NSOrderedAscending:
- NSLog(@"str1<str1 升序");
- break;
- case NSOrderedSame:
- NSLog(@"str1==str2");
- break;
- case NSOrderedDescending:
- NSLog(@"str1>str2 降序");
- default:
- break;
- }
- //直接用逻辑运算符比较的是地址,在常量区的才能使用(stringWithString,initWithString)
- NSString *str3=@"bcd";
- NSString *str4=@"acd";
- if (str3==str4) {
- NSLog(@"相等");
- }
- //isEqualToString(区分大小写)
- BOOL y =[str3 isEqualToString:str4];
- switch (y) {
- case YES:
- NSLog(@"相等");
- break;
- case NO:
- NSLog(@"不相等");
- default:
- break;
- }
-
- }
- return 0;
- }
复制代码
2.substring截取方法
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *str=@"my name is lazy!";
- NSString *s1= [str substringFromIndex:2];
- NSString *s2= [str substringToIndex:2];
- NSLog(@"%@\n%@",s1,s2);
- }
- return 0;
- }
复制代码
3.字符串前后缀查找方法
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *url=@"http://www.itheima.com";
if ([url hasPrefix:@"http://"]||[url hasPrefix:@"https://"] ){
NSLog(@"是一个网址");
}else{
NSLog(@"不是一个网址");
}
NSString *picture=@"xxxx.jpg";
if ([picture hasSuffix:@"jpg"]){
NSLog(@"是图片格式");
}else{
NSLog(@"不是图片格式");
}
}
return 0;
}
4.字符串查找方法
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *str=@"my name is lazy!";
- NSRange range=[str rangeOfString:@"lazy"];
- //如果查找不到。range.location=NSNotFound,range.lenth=0
- //NSNotFound是最大的long类型的数
- if (range.location!=NSNotFound) {
- NSLog(@"位置:%lu,长度:%lu",range.location,range.length);
- }else{
- NSLog(@"未查找到");
- }
- }
- return 0;
- }
复制代码 |
|