首页 > 代码库 > NSString常用的技巧
NSString常用的技巧
1、字符串的末尾追加字符串
NSString * str1 = @"www.";
NSString * str2 = [str1 stringByAppendingString:@"baidu.cn"];
2、字符串指定范围追加字符
NSString * str3 = @"www.cn";
NSRange range = {4,0};
// location代表的时从哪个索引开始插入,length 代表的意思可以覆盖几个字符
NSString * str4 = [str3 stringByReplacingCharactersInRange:range withString:@"baidu"];
3、替换字符
NSString * str5 = @"www.baidu.cn";
NSString * str6 = [str5 stringByReplacingOccurrencesOfString:@"w" withString:@"a"];
4、在字符串中删除特定的某些字符
NSString * str7 = @"www---.baidu.--cn";
NSString * str8 = [str7 stringByReplacingOccurrencesOfString:@"-" withString:@""];
5、去掉字符串中的空格
NSString * str9 = @"www .baidu .cn";
NSString * str10 = [str9 stringByReplacingOccurrencesOfString:@" " withString:@""];
6、将字符串写入文件
NSString * content = @"浙江冰雹,如汤圆大小,万岁";
NSString * path = @"/Users/aplle/Desktop/mytest.txt";
NSError * error;
BOOL isWriteSuccess = [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(isWriteSuccess)
{
NSLog(@"文件创建成功");
}
else
{
NSLog(@"error %@",error);
}
7、从文件中读取字符串
NSString * path = @"/Users/aplle/Desktop/mytest.txt";
NSError * error;
NSString * str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error != nil)
{
NSLog(@"error message %@",error);
}
else
{
NSLog(@"str content %@",str);
}
NSString常用的技巧