NSString用法
1. 字符串写入文件:
[str writeToFile:@"/Users/zhaoxiaohu/Desktop/" atomically:YES encoding:NSUTF8StringEncoding error:&err];
2.字符串从文件读取:
NSString *str = [NSString stringWithContentsOfFile:@"/Users/zhaoxiaohu/Desktop/str.txt" encoding:NSUTF8StringEncoding error:&err];
3.字符串比较函数:
NSComparisonResult result = [str1 compare:str2 options:NSCaseInsensitiveSearch|NSNumericSearch];
返回值:NSOrderedAscending(str1<str2)
NSOrderedDescending(str1>str2)
NSOrderedSame(str1 = str2)
4. 判读字符串是否相等:
[str1 isEqualToString:str3]
5. 检测字符串前后缀:
[url hasPrefix:@"http://"]; 字符串是否以http://开头
[imgName hasSuffix:@".jpg"]; 检测字符串是否以.jpg结尾
6.查找字符串的位置
NSRange range = [str1 rangeofString:str2]; //str1 中找str2
7,得到指定下标的字符
unichar ch = [str1 characterAtIndex:1];
8,以拼接变量的方式组成1个新的字符串
NSString *str3 = [NSString stringWithFormat:@"%@%@",str1,str2];
9.字符串截取 Heima
NSString *str1 = [str substringFromIndex:5];//从指定的下标开始一直截取到最后
NSString *str2 = [str substringToIndex:5];// 截取前面指定个数的字符串
NSRange r1 = {3,4};
NSString *str3 = [str substringWithRange:r1];// 截取指定的范围的字符串.
10.字符串替换: //用 * 替换 a wwwww*****eee
NSString *newStr = [str stringByReplacingOccurrencesOfString:@"a" withString:@"*"];
11. 将字符串转成int类型
int b = [str intValue]; // 前提是字符串是数值类型 @"2"---> 2
12. c字符串与oc字符串相互替换
NSString *str = [NSString stringWithUTF8String:s]; // c -> oc
const char *s1 = [str2 UTF8String]; // oc -> c
13,删除字符串前后的空格.
str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
|
|