任何一个优秀的标准库都需要一个优秀的字符串类,带有Foundation的Objective_C也不例外。实际上Foundation框架中有一个优秀的字符串类--NSString。
NSString的用法总结如下:
1.NSString字符串的创建方法
#pragma mark - 初始化字符串
-(void)CreatingAndInitializingStrings
{
//空字符串
NSString *string = [NSString string];
string = [[NSString alloc]init];
string = @"";
//通过字符串生成字符串
string = [NSString stringWithString:string];
string = [[NSString alloc]initWithString:string];
string = string;
// 组合生成NSString
string = [NSString stringWithFormat:@"Hello, %@",@"World"];
string = [[NSString alloc]initWithFormat:@"Hello, %@",@"World"];
// 通过utf-8字符串
string = [NSString stringWithUTF8String:string.UTF8String];
string = [[NSString alloc]initWithUTF8String:string.UTF8String];
//通过C字符串
const char *cStr = "Hello,world";
//const char *cStr = [string cStringUsingEncoding:NSUTF8StringEncoding];
string = [NSString stringWithCString:cStr encoding:NSUTF8StringEncoding];
string = [[NSString alloc]initWithCString:cStr encoding:NSUTF8StringEncoding];
NSLog(@"CODE:%@",string);
}
2.通过NSString路径读取文件内容
#pragma mark 测试数据
- (NSString *)testData {
// 获取应用中Document文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// 测试数据
NSString *string = @"Hello,World;909011853";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];
NSError *error;
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"错误:%@", error.localizedDescription);
}
return filePath;
}
#pragma mark - 通过NSString路径读取文件内容
-(void)CreateAndInitializingFromFile
{
NSString *filePath = [self testData];
NSError *error;
// 指定编码格式读取
NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
string = [[NSString alloc]initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
// 自动打开,并返回解析的编码模式
NSStringEncoding enc;
string = [NSString stringWithContentsOfFile:filePath usedEncoding:&enc error:&error];
string = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&enc error:&error];
if (error) {
NSLog(@"错误:%@", error.localizedDescription);
}
NSLog(@"FILE:%@",string);
}
3.通过NSURL路径读取文件内容
#pragma mark 通过NSURL路径读取文件内容
-(void)CreateAndInitializingFromURL
{
NSString *filePath = [self testData];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
// 指定编码格式读取
NSString *string = [NSString stringWithContentsOfURL:fileUrl encoding:NSUTF8StringEncoding error:&error];
string = [[NSString alloc] initWithContentsOfURL:fileUrl encoding:NSUTF8StringEncoding error:&error];
// 自动打开,并返回解析的编码模式
NSStringEncoding enc;
string = [NSString stringWithContentsOfURL:fileUrl usedEncoding:&enc error:&error];
string = [[NSString alloc] initWithContentsOfURL:fileUrl usedEncoding:&enc error:&error];
if (error) {
NSLog(@"错误:%@", error.localizedDescription);
}
NSLog(@"URL:%@",string);
}
4.通过NSString或NSURL路径写入NSString
#pragma mark 通过NSString或NSURL路径写入NSString
-(void)WritingFileOrURL
{
NSString *filePath = [self testData];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *error;
NSString *string = @"123123FY";
BOOL write = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
write = [string writeToURL:fileURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"错误:%@", error.localizedDescription);
}else
{
string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"WRITE:%@",string);
}
}
5.获取字符串长度
-(void)GettingLength
{
NSString *string = @"Hello,World";
//长度
NSInteger length = string.length;
NSLog(@"LENGTH0:%ld",length);
// 指定编码格式后的长度
length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"LENGTH1:%ld",length);
// 返回存储时需要指定的长度
length = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"LENGTH2:%ld",length);
}
6.获取Characters和Bytes
-(void)GettingCharactersAndBytes
{
NSString *string = @"Hello,World,Thank U For your like";
// 提取指定位置的character
unichar uch = [string characterAtIndex:3];
NSLog(@"%c",uch);
// 提取Bytes,并返回使用的长度
NSUInteger length = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
const void *bytes;
NSRange range = {0,5};
BOOL gByte = [string getBytes:&bytes maxLength:length usedLength:&length encoding:NSUTF8StringEncoding options:NSStringEncodingConversionAllowLossy range:range remainingRange:nil];
if(gByte)
{
NSLog(@"length:%lu",(unsigned long)length);
}
}
7.获取C字符串
-(void)GettingCString
{
NSString *string = @"Hello,World,Thank U For your like";
// 指定编码格式,获取C字符串
const char *c = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%s", c);
// 获取通过UTF-8转码的字符串
const char *UTF8String = [string UTF8String];
NSLog(@"%s", UTF8String);
}
8.增加字符串生成新的字符串
#pragma mark - 增加字符串
-(void)CombiningString
{
NSString *string = @"Hello,World";
// string后增加字符串并生成一个新的字符串
string = [string stringByAppendingString:@"IOS"];
// string后增加组合字符串并生成一个新的字符串
string = [string stringByAppendingFormat:@"%@",@";hahah"];
// string后增加循环字符串,stringByPaddingToLength:完毕后截取的长度;startingAtIndex:从增加的字符串第几位开始循环增加。
string = [string stringByPaddingToLength:30 withString:@";YoYoYo" startingAtIndex:4];
NSLog(@"APPEND:%@",string);
}
9.字符串分割
-(void)DividingString
{
NSString *string = @"Hello,World;Hello,iOS;Hello,Objective-C";
// 根据指定的字符串分割成数组
NSArray<NSString *> *array = [string componentsSeparatedByString:@";"];
NSLog(@"%@",array);
// 通过系统自带的分割方式分割字符串
NSCharacterSet *set = [NSCharacterSet uppercaseLetterCharacterSet];
array = [string componentsSeparatedByCharactersInSet:set];
NSLog(@"%@",array);
// 返回指定位置后的字符串
NSLog(@"%@",[string substringFromIndex:3]);
// 返回指定范围的字符串
NSRange range = {1,3};
NSLog(@"%@",[string substringWithRange:range]);
// 返回指定位置前的字符串
NSLog(@"%@",[string substringToIndex:3]);
}
10.替换字符串
#pragma mark - 替换字符串
-(void)ReplaceSubstrings
{
NSString *string = @"Hello,World;Hello,iOS;Hello,Objective-C";
NSRange searchRange = {0, string.length};
//全局替换
string = [string stringByReplacingOccurrencesOfString:@"Hello" withString:@"Lovee"];
NSLog(@"%@",string);
// 设置替换的模式,并设置范围
string = [string stringByReplacingOccurrencesOfString:@"Love" withString:@"XIXI" options:NSCaseInsensitiveSearch range:searchRange];
NSLog(@"%@",string);
// 将指定范围的字符串替换为指定的字符串
string = [string stringByReplacingCharactersInRange:searchRange withString:@"1"];
NSLog(@"%@",string);
}
11.识别和比较字符串
-(void)IdentifyingAndComparingStrings
{
NSString *string = @"Hello,world";
NSString *compareStr = @"Hello,Apple";
NSRange searchRange = {0, string.length};
//比较大小
NSComparisonResult result = [string compare:compareStr];
NSLog(@"%ld",result);
//前缀比较
if([string hasPrefix:@"Hello"])
{
NSLog(@"Prefix:Hello");
}
// 后缀比较
if([string hasSuffix:@"hello"])
{
NSLog(@"Suffix:hello");
}
//比较两个字符串是否相同:
if([string isEqualToString:compareStr])
{
NSLog(@"Equal");
}else
{
NSLog(@"UnEquel");
}
// 通过指定的比较模式,比较字符串
result = [string compare:compareStr options:NSCaseInsensitiveSearch];
// 等价
result = [string caseInsensitiveCompare:compareStr];
// 添加比较范围
result = [string compare:compareStr options:NSCaseInsensitiveSearch range:searchRange];
// 增加比较地域
result = [string compare:compareStr options:NSCaseInsensitiveSearch range:searchRange locale:nil];
// 本地化字符串,再比较
result = [string localizedCompare:compareStr];
result = [string localizedStandardCompare:compareStr];
// NSCaseInsensitiveSearch模式
result = [string localizedCaseInsensitiveCompare:compareStr];
// hash值
NSUInteger hash = string.hash;
NSLog(@"hash:%lu", (unsigned long)hash);
}
12.获得共享的前缀
#pragma mark 获得共享的前缀
-(void)GettingSharedPrefix
{
NSString *string = @"Hello,World";
NSString *compareStr = @"Hello,iOS";
// 返回两个字符串相同的前缀
NSString *prefix = [string commonPrefixWithString:compareStr options:NSCaseInsensitiveSearch];
NSLog(@"%@",prefix);
}
13.大小写变化
#pragma mark - 大小写变化
-(void)ChangingCase
{
NSString *string = @"Hello,北京;hello,world;";
NSLocale *locale = [NSLocale currentLocale];
// 单词首字母变大写
NSString *result = string.capitalizedString;
NSLog(@"%@",result);
// 指定系统环境变化
result = [string capitalizedStringWithLocale:locale];
NSLog(@"%@",result);
//全变大写
result = string.uppercaseString;
NSLog(@"%@",result);
result = [string uppercaseStringWithLocale:locale];
NSLog(@"%@",result);
// 全变小写
result = string.lowercaseString;
NSLog(@"%@",result);
result = [string lowercaseStringWithLocale:locale];
NSLog(@"%@",result);
}
14.得到数值
-(void)GetNumberValues
{
NSString *string = @"123";
NSLog(@"doubleValue:%.3f", string.doubleValue);
NSLog(@"floatValue:%.2f", string.floatValue);
NSLog(@"intValue:%d", string.intValue);
NSLog(@"integerValue:%ld", (long)string.integerValue);
NSLog(@"longLongValue:%lld", string.longLongValue);
NSLog(@"boolValue:%d", string.boolValue);
}
15.使用路径
#pragma mark - 使用路径
- (void)WorkingWithPaths {
// 获取应用中Document文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// 路径拆分为数组中的元素
NSArray<NSString *> *pathComponents = documentsDirectory.pathComponents;
// 将数组中的元素拼接为路径
documentsDirectory = [NSString pathWithComponents:pathComponents];
// 加载测试数据
NSString *string = @"阳君;937447974";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
filePath = [documentsDirectory stringByAppendingPathComponent:@"test1.plist"];
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
// 寻找文件夹下包含指定扩展名的文件路径
NSString *outputName;// 相同的前缀
NSArray *filterTypes = [NSArray arrayWithObjects:@"txt", @"plist", nil];
NSUInteger matches = [documentsDirectory completePathIntoString:&outputName caseSensitive:YES matchesIntoArray:&pathComponents filterTypes:filterTypes];
NSLog(@"找到:%lu", (unsigned long)matches);
// 添加路径
filePath = [documentsDirectory stringByAppendingPathComponent:@"test"];
// 添加扩展名
filePath = [filePath stringByAppendingPathExtension:@"plist"];
// 是否绝对路径
NSLog(@"absolutePath:%d", filePath.absolutePath);
// 最后一个路径名
NSLog(@"lastPathComponent:%@", filePath.lastPathComponent);
// 扩展名
NSLog(@"pathExtension:%@", filePath.pathExtension);
// 去掉扩展名
string = filePath.stringByDeletingPathExtension;
// 去掉最后一个路径
string = filePath.stringByDeletingLastPathComponent;
// 批量增加路径,并返回生成的路径
pathComponents = [filePath stringsByAppendingPaths:pathComponents];
// 没啥用
string = filePath.stringByExpandingTildeInPath;
string = filePath.stringByResolvingSymlinksInPath;
string = filePath.stringByStandardizingPath;
}
16.使用URL
#pragma mark 使用URL
- (void)WorkingWithURLs {
NSString *path = @"hello/world";
NSCharacterSet *set = [NSCharacterSet controlCharacterSet];
// 转%格式码
NSString *string = [path stringByAddingPercentEncodingWithAllowedCharacters:set];
NSLog(@"%@",string);
// 转可见
string = string.stringByRemovingPercentEncoding;
NSLog(@"%@",string);
}
17.MutableString修改
-(void)Modifying
{
NSMutableString *mString = [NSMutableString stringWithCapacity:10];
// Format添加
[mString appendFormat:@"%@",@"Hello,"];
NSLog(@"%@",mString);
//添加单一字符串
[mString appendString:@"World"];
NSLog(@"%@",mString);
// 删除指定范围的字符串
NSRange range = {0,3};
[mString deleteCharactersInRange:range];
NSLog(@"%@",mString);
// 指定位置后插入字符串
[mString insertString:@"555555" atIndex:0];
NSLog(@"%@",mString);
// 替换指定范围的字符串
[mString replaceCharactersInRange:range withString:@"111"];
NSLog(@"%@",mString);
// 将指定范围内的字符串替换为指定的字符串,并返回替换了几次
NSUInteger index = [mString replaceOccurrencesOfString:@"1" withString:@"23" options:NSCaseInsensitiveSearch range:range];
NSLog(@"replaceOccurrencesOfString:%lu", (unsigned long)index);
NSLog(@"%@",mString);
// 字符串全替换
[mString setString:@"xixihaha"];
NSLog(@"%@",mString);
}
demo地址:demo