OC基礎(chǔ):NSString

任何一個優(yōu)秀的標(biāo)準(zhǔn)庫都需要一個優(yōu)秀的字符串類,帶有Foundation的Objective_C也不例外。實際上Foundation框架中有一個優(yōu)秀的字符串類--NSString。

NSString的用法總結(jié)如下:

1.NSString字符串的創(chuàng)建方法

#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路徑讀取文件內(nèi)容

#pragma mark 測試數(shù)據(jù)
- (NSString *)testData {
    
    // 獲取應(yīng)用中Document文件夾
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // 測試數(shù)據(jù)
    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路徑讀取文件內(nèi)容
-(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路徑讀取文件內(nèi)容

#pragma mark 通過NSURL路徑讀取文件內(nèi)容
-(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轉(zhuǎn)碼的字符串
    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后增加循環(huán)字符串,stringByPaddingToLength:完畢后截取的長度;startingAtIndex:從增加的字符串第幾位開始循環(huán)增加。
    string = [string stringByPaddingToLength:30 withString:@";YoYoYo" startingAtIndex:4];
    
    NSLog(@"APPEND:%@",string);

}

9.字符串分割

-(void)DividingString
{
    NSString *string = @"Hello,World;Hello,iOS;Hello,Objective-C";
    
    // 根據(jù)指定的字符串分割成數(shù)組
    NSArray<NSString *> *array = [string componentsSeparatedByString:@";"];
    NSLog(@"%@",array);
    
    // 通過系統(tǒng)自帶的分割方式分割字符串
    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);
    
    // 設(shè)置替換的模式,并設(shè)置范圍
    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);
    // 指定系統(tǒng)環(huán)境變化
    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.得到數(shù)值

-(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 {
    
    // 獲取應(yīng)用中Document文件夾
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // 路徑拆分為數(shù)組中的元素
    NSArray<NSString *> *pathComponents = documentsDirectory.pathComponents;
    // 將數(shù)組中的元素拼接為路徑
    documentsDirectory = [NSString pathWithComponents:pathComponents];
    
    // 加載測試數(shù)據(jù)
    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];
    
    // 轉(zhuǎn)%格式碼
    NSString *string = [path stringByAddingPercentEncodingWithAllowedCharacters:set];
    NSLog(@"%@",string);
    
    // 轉(zhuǎn)可見
    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);
    
    // 將指定范圍內(nèi)的字符串替換為指定的字符串,并返回替換了幾次
    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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容