1、大小写转换
1
2
3
4
5
6
7
8
//全部转为大写
[str1 uppercaseString];
//全部转为小写
[str1 lowercaseString];
//首字母大写
[str1 capitalizedString];
2、字符串比较
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1 比较两个字符串内容是否相同
BOOL equal =[str1 isEqualToString:str2];
2 两个字符串内容比较
//NSOrderedAscending 右边 > 左边
//NSOrderedSame 内容相同
//NSOrderedDescending 左边 > 右边
NSComparisonResult result = [str1 compare:str2];
if (result == NSOrderedAscending) {
NSLog(@"右边 > 左边");
}else if(result == NSOrderedSame){
NSLog(@"内容相同");
}else if (result == NSOrderedDescending){
NSLog(@"左边 > 右边");
}
3 忽略大小写进行比较,返回值与compare一样
result = [str1 caseInsensitiveCompare:str2];
if (result == NSOrderedAscending) {
NSLog(@"右边 > 左边");
}else if(result == NSOrderedSame){
NSLog(@"内容相同");
}else if (result == NSOrderedDescending){
NSLog(@"左边 > 右边");
}
3、判断 前缀 后缀
1
2
3
4
//判断字符串是否以指定字符串开头
[str1 hasPrefix:@"aaa"];
//判断字符串是否以指定字符串结尾
[str1 hasSuffix:@"aaa"];
4、字符串搜索,返回range
1
2
3
4
5
6
7
//字符串搜索,返回range
NSRange range = [@"123456" rangeOfString:@"456"];
NSLog(@"%@", NSStringFromRange(range));
//反向搜索
range = [@"123456456qweasasd456" rangeOfString:@"456" options:NSBackwardsSearch];
NSLog(@"%@",NSStringFromRange(range));
//指定range进行搜索
5、字符串截取
1
2
3
4
5
6
7
NSString *str = @"123456789";
//从索引3开始截取 注意:包括索引3
NSLog(@"%@",[str substringFromIndex:3]);
//截取到索引6 注意:包括索引6
NSLog(@"%@",[str substringToIndex:6]);
//截取 指定的范围 NSMakeRange(3, 3) 即 从索引3(包括索引3)开始截取三个字符
NSLog(@"%@",[str substringWithRange:NSMakeRange(3, 3)]);
6、分割 拼接 字符串
1
2
3
4
5
//分割字符串
NSArray *array = [@"1,2,3,4,5,6" componentsSeparatedByString:@","];
//拼接字符串
NSString * string = [array componentsSeparatedByString:@","];
7、路径 相关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//将数组拼接为路径
components = @[@"Users",@"Desktop",@"Finder"];
NSString *path = [NSString pathWithComponents:components];
//反之 将路径分割为数组
NSArray * components1 = [path pathComponents];
//将一个路径分割成一个数组
NSArray *array1 = [path pathComponents];
//判断是否为绝对路径(依据:是否以'/'开始)
BOOL isAbsolute = [path isAbsolutePath];
//获取最后一个目录
[path lastPathComponent];
//删除最后一个目录
[path stringByDeletingLastPathComponent];
//拼接一个目录
[path stringByAppendingPathComponent:@"aaa"]; -> /Users/CentralPerk/Desktop/aaa
8、拓展名 相关
1
2
3
4
5
6
7
8
//获取拓展名,不包括点
NSString * str = @"Users/CentralPerk/Desktop/test.txt";
[str pathExtension] -> @"txt";
NSString * string = @"大海";
//添加拓展名,不需要带点
NSString * str2 = [string stringByAppendingPathExtension:@"mp3"]; -> @"大海.mp3"
//删除拓展名,与点一快删除
[str2 stringByDeletingPathExtension] = @"大海";
9、字符串 转 int double float
1
2
3
4
5
//字符串转为 int double float
NSString *str3 = @"123";
[str3 intValue];
[str3 doubleValue];
[str3 floatValue];
10、字符相关
1
2
//取索引3的字符
unichar c = [str3 characterAtIndex:2];
11、转为C语言的字符串
1
const char *s = [str3 UTF8String];