本文首发于我的个人博客:『不羁阁』 https://bujige.net 文章链接:https://bujige.net/blog/iOS-Foundation-String.html 本文对Foundation框架中的字符串类(NSString、NSMutableString)的使用做一个详细的总结。
NSString *str = @"abc";
NSString *str = [[NSString alloc]initWithFormat:@"abc"];
NSString *str = [NSString stringWithFormat:@"abc"];
// 用来保存错误信息
NSError *error = nil;
// 读取文件内容
NSString *str = [NSString stringWithContentsOfFile:@"/Users/Walkers/Desktop/test.txt" encoding:NSUTF8StringEncoding error:&error];
// 如果有错误信息
if (error) {
NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
NSLog(@"读取成功, 文件内容是:\n%@", str);
}
输出结果:读取成功, 文件内容是:abc
NSString *str = @"abc";
BOOL flag = [str writeToFile:@"/Users/Walkers/Desktop/test.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (flag == 1)
{
NSLog(@"写入成功");
}
输出结果:写入成功
NSString *str1 = @"abc";
BOOL flag = [str1 writeToFile:@"/Users/Walkers/Desktop/test.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *str2 = @"xyz";
[str2 writeToFile:@"/Users/Walkers/Desktop/test.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *str = [NSString stringWithContentsOfFile:@"/Users/Walkers/Desktop/test.txt" encoding:NSUTF8StringEncoding error:&error];
NSLog(@"str = %@", str);
输出结果: xyz
NSURL *url = [NSURL URLWithString:@"file:///Users/Walkers/Desktop/str.txt"];
NSURL *url = [NSURL fileURLWithPath:@"/Users/Walkers/Desktop/str.txt"];
// 用来保存错误信息
NSError *error = nil;
// 创建URL路径
NSURL *url = [NSURL fileURLWithPath:@"/Users/Walkers/Desktop/test.txt"];
// 读取文件内容
NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
// 如果有错误信息
if (error) {
NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
NSLog(@"读取成功, 文件内容是:\n%@", str);
}
输出结果:读取成功, 文件内容是:abc
NSString *str = @"Walkers";
[str writeToURL:[NSURL URLWithString:@"/Users/Walkers/Desktop/str.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
- (NSString *)uppercaseString;
- (NSString *)lowercaseString;
- (NSString *)capitalizedString;
- (BOOL)isEqualToString:(NSString *)aString;
NSString *str1 = @"abc";
NSString *str2 = [NSString stringWithFormat:@"abc"];
if ([str1 isEqualToString:str2]) {
NSLog(@"字符串内容一样");
}
if (str1 == str2) {
NSLog(@"字符串地址一样");
}
- (NSComparisonResult)compare:(NSString *)string;
NSString *str1 = @"abc";
NSString *str2 = @"abd";
switch ([str1 compare:str2]) {
case NSOrderedAscending:
NSLog(@"后面一个字符串大于前面一个");
break;
case NSOrderedDescending:
NSLog(@"后面一个字符串小于前面一个");
break;
case NSOrderedSame:
NSLog(@"两个字符串一样");
break;
}
输出结果:后面一个字符串大于前面一个
(NSComparisonResult) caseInsensitiveCompare:(NSString *)string;
NSString *str1 = @"abc";
NSString *str2 = @"ABC";
switch ([str1 caseInsensitiveCompare:str2]) {
case NSOrderedAscending:
NSLog(@"后面一个字符串大于前面一个");
break;
case NSOrderedDescending:
NSLog(@"后面一个字符串小于前面一个");
break;
case NSOrderedSame:
NSLog(@"两个字符串一样");
break;
}
输出结果:两个字符串一样
- (BOOL)hasPrefix:(NSString *)aString;
NSString *str = @"http://jianshu.com/img/Walkers.gif";
if ([str hasPrefix:@"http://"]) {
NSLog(@"包含http://");
} else {
NSLog(@"不包含http://");
}
输出结果:包含http://
- (BOOL)hasSuffix:(NSString *)aString;
NSString *str = @"http://jianshu.com/img/Walkers.gif";
if ([str hasSuffix:@".gif"]) {
NSLog(@"动态图片");
} else {
NSLog(@"不是动态图片");
}
输出结果:动态图片
- (NSRange)rangeOfString:(NSString *)aString;
NSString *str = @"http://jianshu.com/img/Walkers.gif";
NSRange range = [str rangeOfString:@"Walkers"];
if (range.location == NSNotFound) {
NSLog(@"str中没有需要查找的字符串");
} else {
NSLog(@"str中有需要查找的字符串");
NSLog(@"location = %lu, length = %lu", range.location, range.length);
}
输出结果:
str中有需要查找的字符串
location = 23, length = 7
- (NSString *)substringFromIndex:(NSUInteger)from;
NSString *str = @"<head>程序员</head>";
str = [str substringFromIndex:6];
NSLog(@"str = %@", str);
输出结果: 程序员</head>
- (NSString *)substringToIndex:(NSUInteger)to;
NSString *str = @"<head>程序员</head>";
str = [str substringToIndex:6];
NSLog(@"str = %@", str);
输出结果: <head>
- (NSString *)substringWithRange:(NSRange)range;
NSString *str = @"<head>程序员</head>";
NSRange range;
/*
range.location = 6;
range.length = 3;
*/
range.location = [str rangeOfString:@">"].location + 1;
range.length = [str rangeOfString:@"</"].location - range.location;
NSString *res = [str substringWithRange:range];
NSLog(@"res = %@", res);
输出结果: 程序员
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement;
NSString *str = @"http:**jianshu.com*img*Walkers.gif";
NSString *newStr = [str stringByReplacingOccurrencesOfString:@"*" withString:@"/"];
NSLog(@"newStr = %@", newStr);
输出结果: newStr = http://jianshu.com/img/Walkers.gif
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
NSString *str = @" http://jianshu.com/img/Walkers.gif "; NSString *newStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSLog(@"str =|%@|", str); NSLog(@"newStr =|%@|", newStr); 输出结果: str =| http://jianshu.com/img/Walkers.gif | newStr =|http://jianshu.com/img/Walkers.gif|
NSString *str = @"***http://jianshu.com/img/Walkers.gif***"; NSString *newStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"*"]]; NSLog(@"str =|%@|", str); NSLog(@"newStr =|%@|", newStr); 输出结果: str =|***http://jianshu.com/img/Walkers.gif***| newStr =|http://jianshu.com/img/Walkers.gif|
- (BOOL)isAbsolutePath;
// 其实就是判断是否以/开头
// NSString *str = @"/Users/Walkers/Desktop/test.txt"; // 绝对路径
NSString *str = @"Users/Walkers/Desktop/test.txt"; // 不是绝对路径
if ([str isAbsolutePath]) {
NSLog(@"是绝对路径");
}else {
NSLog(@"不是绝对路径");
}
输出结果:不是绝对路径
- (NSString *)lastPathComponent;
// 截取最后一个/后面的内容
NSString *str = @"/Users/Walkers/Desktop/test.txt";
NSString *component = [str lastPathComponent];
NSLog(@"component = %@", component);
输出结果:component = test.txt
- (NSString *)stringByDeletingLastPathComponent;
// 其实就是删除最后一个/和之后的内容
NSString *str = @"/Users/Walkers/Desktop/test.txt";
NSString *newStr = [str stringByDeletingLastPathComponent];
NSLog(@"newStr = %@", newStr);
输出结果:newStr = /Users/Walkers/Desktop
- (NSString *)stringByAppendingPathComponent:(NSString *)str;
stringByAppendingString:
或者stringByAppendingFormat:
拼接字符串内容// 其实就是在最后面加上/和要拼接得内容
// 注意会判断后面有没有/有就不添加了, 没有就添加, 并且如果有多个会替换为1个
// NSString *str = @"/Users/Walkers/Desktop";
NSString *str = @"/Users/Walkers/Desktop/";
NSString *newStr = [str stringByAppendingPathComponent:@"abc"];
NSLog(@"newStr = %@", newStr);
输出结果:newStr = /Users/Walkers/Desktop/abc
- (NSString *)pathExtension;
// 其实就是从最后面开始截取.之后的内容
// NSString *str = @"test.txt";
NSString *str = @"abc.test.txt";
NSString *extension = [str pathExtension];
NSLog(@"extension = %@", extension);
输出结果:extension = txt
- (NSString *)stringByDeletingPathExtension;
// 其实就是删除从最后面开始.之后的内容
// NSString *str = @"test.txt";
NSString *str = @"abc.test.txt";
NSString *newStr = [str stringByDeletingPathExtension];
NSLog(@"newStr = %@", newStr);
输出结果:newStr = abc.test
- (NSString *)stringByAppendingPathExtension:(NSString *)str;
// 其实就是在最后面拼接上.和指定的内容
NSString *str = @"abc";
NSString *newStr = [str stringByAppendingPathExtension:@"gif"];
NSLog(@"newStr = %@", newStr);
输出结果:newStr = abc.gif
- (NSUInteger)length;
- (unichar)characterAtIndex:(NSUInteger)index;
NSString *str = @"abc";
NSString *newStr = [str uppercaseString];
NSLog(@"%@", newStr);
输出结果:ABC
NSString *str = @"ABC";
NSString *newStr2 = [str lowercaseString];
NSLog(@"%@", newStr2);
输出结果:abc
NSString *str = @"abc";
NSString *newStr = [str capitalizedString];
NSLog(@"%@", newStr);
输出结果:Abc
- (double)doubleValue;
- (float)floatValue;
- (int)intValue;
NSString *str1 = @"110";
NSString *str2 = @"10";
int res = str1.intValue + str2.intValue;
NSLog(@"res = %i", res);
NSString *str1 = @"110";
NSString *str2 = @"10.1";
double res = str1.doubleValue + str2.doubleValue;
NSLog(@"res = %f", res);
- (char *)UTF8String;
NSString *str = @"abc";
const char *cStr = [str UTF8String];
NSLog(@"cStr = %s", cStr);
char *cStr = "abc";
NSString *str = [NSString stringWithUTF8String:cStr];
NSLog(@"str = %@", str);
// 改变了指针的指向, 并没有修改字符串
NSString *str = @"abc"; // 一开始str指向@"abc"对应的内存
str = @"xyz"; //修改了str指针的指向,让它指向@"xyz"对应的内存
// 生成了一个新的字符串, 并没有修改字符串
NSString *newStr = [str substringFromIndex:1];
NSLog(@"str = %@", str);
NSLog(@"newStr = %@", newStr);
输出结果:
str = xyz
newStr = yz
执行完NSString *str = @"abc";
后在内存中的表现如下图所示,str指向@"abc"对应的内存
1.png
执行完str = @"xyz";
后在内存中的表现如下图所示,该语句修改了str指针的指向,让它指向@"xyz"对应的内存
2.png
执行完NSString *newStr = [str substringFromIndex:1];
,在内存中的表现如下图所示,该语句生成了一个新的字符串,并没有修改原有字符串
3.png
NSMutableString *str = [NSMutableString string];
NSLog(@"str = %@", str);
// 修改原有字符串, 没有生成新的字符串
[str appendString:@"abc"];
NSLog(@"str = %@", str);
[str appendString:@" xyz"];
NSLog(@"str = %@", str);
执行完NSMutableString *str = [NSMutableString string];
后,在内存中的表现如下图所示
4.png
执行完[str appendString:@"abc"];
后,在内存中的表现如下图所示,该语句修改了原有字符串,并没有生成新的字符串
5.png
接着执行[str appendString:@" xyz"];
后,在内存中的表现如下图所示,该语句同样修改了原有字符串,并没有生成新的字符串
6.png
- (void)appendString:(NSString *)aString;
NSMutableString *str = [NSMutableString stringWithFormat:@"http://jianshu.com/img/Walkers"];
NSLog(@"str = %@", str);
[str appendString:@".gif"];
NSLog(@"str = %@", str);
输出结果:
str = http://jianshu.com/img/Walkers
str = http://jianshu.com/img/Walkers.gif
- (void)appendFormat:(NSString *)format, ...;
NSMutableString *str = [NSMutableString stringWithFormat:@"Walkers"];
[str appendFormat:@" age is %i", 23];
NSLog(@"str = %@", str);
输出结果:str = Walkers age is 23
- (void)deleteCharactersInRange:(NSRange)range;
NSMutableString *str = [NSMutableString stringWithFormat:@"http://jianshu.com/img/Walkers"];
// 一般情况下利用rangeOfString和deleteCharactersInRange配合删除指定内容
NSRange range = [str rangeOfString:@"http://"];
[str deleteCharactersInRange:range];
NSLog(@"str = %@", str);
输出结果:str = jianshu.com/img/Walkers
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
NSMutableString *str = [NSMutableString stringWithFormat:@"jianshu.com/img/Walkers"];
[str insertString:@"http://" atIndex:0];
NSLog(@"str = %@", str);
输出结果:str = http://jianshu.com/img/Walkers
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString;
NSMutableString *str = [NSMutableString stringWithFormat:@"http://jianshu.com/img/Walkers.gif"];
NSRange range = [str rangeOfString:@"Walkers"];
[str replaceOccurrencesOfString:@"Walkers" withString:@"abc" options:0 range:range];
NSLog(@"str = %@", str);
输出结果:str = http://jianshu.com/img/abc.gif
@"abc"
这种方式创建的字符串始终是NSString,不是NSMutalbeString。所以下面的代码创建的还是NSString,此时使用可变字符串的函数,无法操作字符串。NSMutableString *s1 = @"abc";
[strM insertString:@"my name is " atIndex:0]; // 会报错