三種型別 NSCFConstantString、NSCFString、NSTaggedPointerString
######1、NSCFConstantString字串常量 NSCFConstantString物件,只要字串內容不變,就不會分配新的記憶體地址,無論你是賦值、retain、copy。這種優化在大量使用NSString的情況下可以節省記憶體,提高效能
NSString *str1 = @"aaa";
NSString *str2 = [NSString stringWithString:@"aaa"];// XCode會提示 其實就是 str2 = @"aaa";
NSString *str3 = [[NSString alloc] initWithString:@"aaa"];// XCode會提示 其實就是 str3 = @"aaa";
// 三個都是一樣,字串常量NSCFConstantString,同一個地址
複製程式碼
######2、NSTaggedPointerString 當數字、英文、符號等的ASCII字元組成字串,長度小於等於9的時候會自動成為NSTaggedPointerString型別(TaggedPointer專門用來儲存小的物件)
// NSTaggedPointerString
NSString *str5 = [NSString stringWithFormat:@"123456789"];
NSString *str6 = [NSString stringWithFormat:@"123ASD"];
複製程式碼
NSTaggedPointerString是假物件,指標的值不再是地址了,而是真正的值。所以,實際上它不再是一個物件了,它只是一個披著物件皮的普通變數而已!所以,它的記憶體並不儲存在堆中,也不需要malloc和free。
NSString *str1 = [NSString stringWithFormat:@"1"];
NSString *str2 = [NSString stringWithFormat:@"2"];
NSString *str3 = [NSString stringWithFormat:@"a"];
NSString *str4 = [NSString stringWithFormat:@"b"];
NSLog(@"=====%p",str1);
NSLog(@"=====%p",str2);
NSLog(@"=====%p",str3);
NSLog(@"=====%p",str4);
/*
輸出 = =====0xa000000000000311 ASCII碼錶31就是1
輸出 = =====0xa000000000000321 32就是2
輸出 = =====0xa000000000000611 61就是a
輸出 = =====0xa000000000000621 62就是b
*/
複製程式碼
#####3、NSCFString 字串(可能是非 ASCII 字元)長度大於9的非常量字串,是__NSCFString型別。 NSCFString物件是一種NSString子類,儲存在堆上,不屬於字串常量物件。該物件建立之後和其他的Obj物件一樣引用計數為1,對其執行retain和release將改變其retainCount。
NSString *str1 = [NSString stringWithFormat:@"1234567890"];
NSString *str2 = [[NSString alloc] stringWithFormat:@"123你好"];
// NSCFString物件是一種NSString子類,儲存在堆上,不屬於字串常量物件。該物件建立之後和其他的Obj物件一樣引用計數為1,對其執行retain和release將改變其retainCount。
複製程式碼
各種屬性
//字串長度
@property (readonly) NSUInteger length;
//選取字串對應下表的字元
- (unichar)characterAtIndex:(NSUInteger)index;
複製程式碼
初始化方法
// 字串的init初始化方法
- (instancetype)init NS_DESIGNATED_INITIALIZER;
// NSCoding協議-例項化序列化
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
// 指定緩衝區,編碼和位元組長度初始化NSString物件
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;
// 指定unichar字元,位元組長度初始化NSString物件
- (instancetype)initWithCharacters:(constunichar *)characters length:(NSUInteger)length;
// 轉化為NSString物件
- (instancetype)initWithUTF8String:(constchar *)nullTerminatedCString;
// 指定字串初始化為NSString物件
- (instancetype)initWithString:(NSString *)aString;
// 格式化多個字串初始化NSString物件
- (instancetype)initWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 格式化字串初始化NSString物件
- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argListNS_FORMAT_FUNCTION(1,0);
// 本地化格式化多個字串初始化NSString物件
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...NS_FORMAT_FUNCTION(1,3);
// 本地化格式化字串初始化NSString物件
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argListNS_FORMAT_FUNCTION(1,0);
// 指定編碼轉化NSData資料
- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
// 指定編碼和位元組數初始化NSString物件
- (instancetype)initWithBytes:(constvoid *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;
// 指定緩衝區,編碼和位元組數初始化NSString物件
- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer;
// 初始化空字串
+ (instancetype)string;
// 初始化NSString字串
+ (instancetype)stringWithString:(NSString *)string;
// 返回指定長度unichar的C字串
+ (instancetype)stringWithCharacters:(constunichar *)characters length:(NSUInteger)length;
// 轉化C字串為UTF8串
+ (instancetype)stringWithUTF8String:(constchar *)nullTerminatedCString;
// 初始化NSString物件昂,這種建立方式會自動釋放記憶體,很常用的一種方式
+ (instancetype)stringWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 初始化NSString自動釋放記憶體,本地化
+ (instancetype)localizedStringWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 初始化C字串並且指定編碼,在這裡需要手動釋放記憶體(init)
- (instancetype)initWithCString:(constchar *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
// 初始化C字串並且指定編碼,在這裡需要自動釋放記憶體
+ (instancetype)stringWithCString:(constchar *)cString encoding:(NSStringEncoding)enc;
// 讀取URL地址資料轉化為字串並且指定編碼,在這裡init建立需要手動釋放記憶體,已經知道編碼
- (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
// 讀取FILE地址資料轉化為字串並且指定編碼,同樣需要手動釋放記憶體,已經知道編碼
- (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
// 讀取URL地址資料轉化為字串並且指定編碼,,這裡會自動釋放記憶體,已經知道編碼
+ (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
// 讀取FILE地址資料轉化為字串並且指定編碼,這裡也會自定釋放記憶體,已經知道編碼
+ (instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
// 讀取URL地址資料轉化為字串並且指定編碼,在這裡init建立需要手動釋放記憶體,不知道編碼
- (instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 讀取FILE地址資料轉化為字串並且指定編碼,同樣需要手動釋放記憶體,不知道編碼
- (instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 取URL地址資料轉化為字串並且指定編碼,,這裡會自動釋放記憶體,不知道編碼
+ (instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 讀取FILE地址資料轉化為字串並且指定編碼,這裡也會自定釋放記憶體,不知道編碼
+ (instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
複製程式碼
字串擷取
/* 防止Emoji表情擷取問題,應該這樣子使用:
[str substringFromIndex:[str rangeOfComposedCharacterSequenceAtIndex:index].location]
[str substringToIndex:NSMaxRange([str rangeOfComposedCharacterSequenceAtIndex:index])]
[str substringWithRange:[str rangeOfComposedCharacterSequencesForRange:range]
*/
// 擷取指定位置Index之後字串
- (NSString *)substringFromIndex:(NSUInteger)from;
// 從索引0第一個字串開始,擷取指定長度的字串
- (NSString *)substringToIndex:(NSUInteger)to;
// 擷取字串的指定段,返回值為NSString
- (NSString *)substringWithRange:(NSRange)range; // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences
// 擷取字串的指定段
- (void)getCharacters:(unichar *)buffer range:(NSRange)range;
複製程式碼
字串對比
//字串進行比較
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
NSCaseInsensitiveSearch =1,//兩個字串的比較不區分大小寫
NSLiteralSearch = 2,//兩個字串的比較區分大小寫
NSBackwardsSearch =4,//從字串末尾開發查詢搜尋
NSAnchoredSearch =8,//搜尋有限制範圍的字串
NSNumericSearch = 64,//根據字串裡的數字來計算順序
NSDiacriticInsensitiveSearchNS_ENUM_AVAILABLE(10_5,2_0) =128,
NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5,2_0) =256,//可以忽略字串的寬度(長度)比較結果
NSForcedOrderingSearchNS_ENUM_AVAILABLE(10_5,2_0) =512,//忽略不區分大小寫比較的選項
NSRegularExpressionSearchNS_ENUM_AVAILABLE(10_7,3_2) =1024 //
};
/**
比較字串
@param string self與string比較
@param mask NSStringCompareOptions條件
@param rangeOfReceiverToCompare 指定段進行比較(只是對self)
@param locale 某些條件還有本地化語言環境
@return NSComparisonResult NSOrderedAscending大 NSOrderedSame相同 NSOrderedDescending小
*/
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale;
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
// 不區分大小寫比較字串
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
// 本地化比較字串
- (NSComparisonResult)localizedCompare:(NSString *)string;
//不區分大小寫以及本地化比較字串
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
// 本地化標準字串比較--它排序的方式和 Finder 一樣。它對應的選項是 NSCaseInsensitiveSearch、NSNumericSearch、NSWidthInsensitiveSearch 以及 NSForcedOrderingSearch。如果我們要在 UI 上顯示一個檔案列表,用它就最合適不過了
/*
//OC之按中文排序(localizedStandardCompare)
NSArray *arrs=@[@"小雨",@"安安",@"小風",@"榮榮",@"張濤",@"李文榮"];
NSArray *sortarr=[arrs sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 localizedStandardCompare:obj2];//中文按照拼音的首字母排序
}];
*/
- (NSComparisonResult)localizedStandardCompare:(NSString *)string NS_AVAILABLE(10_6, 4_0);
// 判斷兩個字串是否內容一致
- (BOOL)isEqualToString:(NSString *)aString;
複製程式碼
字串搜尋查詢
// 是否包含字首(以str開頭)
- (BOOL)hasPrefix:(NSString *)str;
// 是否包含字尾(以str結尾)
- (BOOL)hasSuffix:(NSString *)str;
// 獲取公共字首 加入self=@“ABC1234” str=@“ABC789”,返回就是ABC
- (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask;
// 是否包含字串
- (BOOL)containsString:(NSString *)str NS_AVAILABLE(10_10, 8_0);
// 本地化是否包含字串(不區分大小寫)
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str NS_AVAILABLE(10_10, 8_0);
// 本地化是否包含字串(標準)
- (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
// 本地化搜尋字串範圍(標準)
- (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
//搜尋(指定字串)
- (NSRange)rangeOfString:(NSString *)searchString;
//搜尋(指定字串,條件)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
//搜尋(指定字串,條件,範圍)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
//搜尋(指定字串,條件,範圍,本地化)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(nullable NSLocale *)locale;
// 搜尋(指定字符集合)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;
// 搜尋(指定字符集合,條件)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask;
// 搜尋(指定字符集合,條件,範圍)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
// 用字串的字元編碼指定索引查詢位置
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
// 用字串的字元編碼指定區域段查詢位置
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range;
複製程式碼
字串轉換
@property (readonly) double doubleValue;
@property (readonly) float floatValue;
@property (readonly) int intValue;
@property (readonly) NSInteger integerValue;
@property (readonly) long long longLongValue;
@property (readonly) BOOL boolValue;
//將字串的所有字元轉化成大寫
@property (readonly,copy)NSString *uppercaseString;
//將字串的所有字元轉化為小寫
@property (readonly,copy)NSString *lowercaseString;
// 所有單詞的首字母轉化成大寫
@property (readonly,copy)NSString *capitalizedString;
//所有字元轉化成大寫 本地化
- (NSString *)uppercaseStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//所有字串轉化成小寫 本地化
- (NSString *)lowercaseStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//所有單詞首字母轉化成大寫 本地化
- (NSString *)capitalizedStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//預設本地化所有字元轉化成大寫
@property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
//預設本地化所有字串轉化成小寫
@property (readonly, copy) NSString *localizedLowercaseString NS_AVAILABLE(10_11, 9_0);
//預設本地化所有單詞首字母轉化成大寫
@property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
複製程式碼
字串分行,分段
//////////分行//////////
//1.指定範圍,分行取字串
- (void)getLineStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)lineEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//2.獲取指定範圍該行的範圍
- (NSRange)lineRangeForRange:(NSRange)range;
//////////分段//////////
//3.指定範圍,分段取字串
- (void)getParagraphStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)parEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//4.獲取指定範圍該段落的範圍
- (NSRange)paragraphRangeForRange:(NSRange)range;
//////////字串分行,分段//////////
NSString *string = @"123 456\nABC,DEF\nabc.def";
//獲取該行的範圍(指定範圍)
NSRange range1 = [string lineRangeForRange:NSMakeRange(0, 10)];
NSLog(@"%ld 行長度: %ld", range1.location, range1.length);
//輸出: 0 行長度: 16
//獲取該段落範圍(指定範圍)
NSRange range2 = [string paragraphRangeForRange:NSMakeRange(0, 3)];
NSLog(@"%ld 段落長度: %ld", range2.location, range2.length);
//輸出: 0 段落長度: 8
複製程式碼
字串列舉方法
typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
// Pass in one of the "By" options:
NSStringEnumerationByLines = 0, // 按行
NSStringEnumerationByParagraphs = 1, // 按段落
NSStringEnumerationByComposedCharacterSequences = 2, // 按字元順序
NSStringEnumerationByWords = 3, // 按單詞,字
NSStringEnumerationBySentences = 4, // 按句子
NSStringEnumerationReverse = 1UL << 8, // 反向遍歷
NSStringEnumerationSubstringNotRequired = 1UL << 9, // 不需要子字串
NSStringEnumerationLocalized = 1UL << 10 // 本地化
};
// 檢查是否在指定範圍內是否有匹配的字串
- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
// 列舉列舉字串所有行
- (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
//////////使用例子//////////
NSString *string = @"123456\nABCDEF\nabcdef
//1.列舉(按行)
[string enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {
NSLog(@"每行: %@", line);
}];
//輸出: 每行: 123456
//輸出: 每行: ABCDEF
//輸出: 每行: abcdef
//2.列舉(範圍,條件)
[string enumerateSubstringsInRange:NSMakeRange(5, 10) options:NSStringEnumerationByLines usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
NSLog(@"%@", substring);
NSLog(@"%ld %ld", substringRange.location, substringRange.length);
NSLog(@"%ld %ld", enclosingRange.location, enclosingRange.length);
}];
//輸出: 6
//輸出: 5 1
//輸出: 5 2
//輸出: ABCDEF
//輸出: 7 6
//輸出: 7 7
//輸出: a
//輸出: 14 1
//輸出: 14 1
複製程式碼
編碼相關
NS_ENUM(NSStringEncoding) {
NSASCIIStringEncoding = 1, /* 0..127 only */
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5,
NSSymbolStringEncoding = 6,
NSNonLossyASCIIStringEncoding = 7,
NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
NSISOLatin2StringEncoding = 9,
NSUnicodeStringEncoding = 10,
NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
NSWindowsCP1253StringEncoding = 13, /* Greek */
NSWindowsCP1254StringEncoding = 14, /* Turkish */
NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
NSMacOSRomanStringEncoding = 30,
NSUTF16StringEncoding = NSUnicodeStringEncoding, /* An alias for NSUnicodeStringEncoding */
NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
// UTF8編碼值
@property (nullable, readonly) const char *UTF8String;
// 最快編碼值
@property (readonly) NSStringEncoding fastestEncoding;
// 自小編碼值
@property (readonly) NSStringEncoding smallestEncoding;
// 選擇編碼,是否允許有損編碼
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy;
// 選擇編碼
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
// 判斷是否可以無損編碼
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;
// C字元編碼轉換
- (nullable const char *)cStringUsingEncoding:(NSStringEncoding)encoding ;
// 判斷C字元轉化是否可以成功
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding;
// 指定快取區轉換
- (BOOL)getBytes:(nullable void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(nullable NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(nullable NSRangePointer)leftover;
// 對字串進行編碼時所需的最大位元組數
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;
// 對字串進行編碼時所需的位元組數
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc;
// 可用字串編碼
+ (const NSStringEncoding *)availableStringEncodings;
// 本地化編碼名稱
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding;
// 預設C字串編碼
+ (NSStringEncoding)defaultCStringEncoding;
// unicode正規化D標準化
@property (readonly,copy)NSString *decomposedStringWithCanonicalMapping;
// unicode正規化c標準化
@property (readonly,copy)NSString *precomposedStringWithCanonicalMapping;
// unicode正規化KD標準化
@property (readonly,copy)NSString *decomposedStringWithCompatibilityMapping;
// unicode正規化KC標準化
@property (readonly,copy)NSString *precomposedStringWithCompatibilityMapping;
複製程式碼
字串分割
/*
NSCharacterSet
controlCharacterSet 控制符
whitespaceCharacterSet 空格符
whitespaceAndNewlineCharacterSet 空格換行符
decimalDigitCharacterSet 小數
letterCharacterSet 文字
lowercaseLetterCharacterSet 小寫字母
uppercaseLetterCharacterSet 大寫字母
nonBaseCharacterSet 非基礎
alphanumericCharacterSet 數字字母
decomposableCharacterSet 可分解
illegalCharacterSet 非法
punctuationCharacterSet 標點
capitalizedLetterCharacterSet 大寫
symbolCharacterSet 符號
newlineCharacterSet 換行符
*/
//分割(指定字串)
- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;
//分割(指定字符集合)
- (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0);
//////////使用例子//////////
NSString *string = @"A_B_c_D_E_F";
//分割(指定字串)
NSArray *resultArr1 = [string componentsSeparatedByString:@"_"];
NSLog(@"%@", resultArr1);
//輸出: (A, B, c, D, E, F)
//分割(指定字符集合)
NSArray *resultArr2 = [string componentsSeparatedByCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
NSLog(@"%@", resultArr2);
//輸出: ("A_B_" , "_D_E_F")
複製程式碼
字串操作(修剪,填充,摺疊,替換)
NSString *string = @"3EWRs a;af";
//////////修剪//////////
NSString *result1 = [string stringByTrimmingCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
NSLog(@"%@", result1);
//輸出: 3EWRs a;
//////////填充//////////
NSString *result2 = [string stringByPaddingToLength:20 withString:@"填充" startingAtIndex:1];
NSLog(@"%@", result2);
//輸出: 3EWRs a;af充填充填充填充填充填
//////////摺疊//////////
NSString *result3 = [string stringByFoldingWithOptions:NSNumericSearch locale:[NSLocale systemLocale]];
NSLog(@"%@", result3);
//輸出: 3EWRs a;af
//////////替換//////////
//替換(指定字串)
NSString *result4 = [string stringByReplacingOccurrencesOfString:@" " withString:@"替換"];
NSLog(@"%@", result4);
//輸出: 3EWRs替換a;af
//替換(指定字串,條件,範圍)
NSString *result5 = [string stringByReplacingOccurrencesOfString:@"a" withString:@"替換" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length - 2)];
NSLog(@"%@", result5);
//輸出: 3EWRs 替換;af
//替換(指定範圍)
NSString *result6 = [string stringByReplacingCharactersInRange:NSMakeRange(0, string.length) withString:@"替換"];
NSLog(@"%@", result6);
//輸出: 替換
複製程式碼
字串翻譯
//翻譯選擇
NSStringTransformLatinToKatakana 拉丁->片假名
NSStringTransformLatinToHiragana 拉丁->平假名
NSStringTransformLatinToHangul 拉丁->韓語
NSStringTransformLatinToArabic 拉丁->阿拉伯語
NSStringTransformLatinToHebrew 拉丁->希伯來語
NSStringTransformLatinToThai 拉丁->泰國
NSStringTransformLatinToCyrillic 拉丁->西裡爾字母
NSStringTransformLatinToGreek 拉丁->希臘
NSStringTransformToLatin 拉丁
NSStringTransformMandarinToLatin 普通話->拉丁
NSStringTransformHiraganaToKatakana 平假名->片假名
NSStringTransformFullwidthToHalfwidth 全形->半形
NSStringTransformToXMLHex XML16進位制
NSStringTransformToUnicodeName Unicode名
NSStringTransformStripCombiningMarks 結合地帶商標
NSStringTransformStripDiacritics 帶音符
//////////字串翻譯//////////
NSString *dalian = @"大連";
NSString *result = [dalian stringByApplyingTransform:NSStringTransformMandarinToLatin reverse:NO];
NSLog(@"%@", result);
//輸出: dà lián
複製程式碼
字串寫入
//////////字串寫入//////////
//寫入到指定路徑,編碼的檔案中
[string writeToFile:@"/Users/Desktop/LuisX.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
//寫入到指定URL,編碼的檔案中
[string writeToURL:[NSURL URLWithString:@"file://LuisX.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
複製程式碼
NSMutableString
NSMutableString *str = [NSMutableString stringWithString:@"string"];
//////////插入//////////
[str insertString:@"123" atIndex:2];
NSLog(@"%@", str);
//輸出: st123ring
//////////刪除//////////
[str deleteCharactersInRange:NSMakeRange(2, 2)];
NSLog(@"%@", str);
//輸出: st3ring
//////////拼接//////////
[str appendString:@"456"];
NSLog(@"%@", str);
//輸出: st3ring456
//////////格式化拼接//////////
[str appendFormat:@"7 89"];
NSLog(@"%@", str);
//輸出: st3ring4567 89
//////////設定新字串//////////
[str setString:@"string"];
NSLog(@"%@", str);
//輸出: string
//////////字串替換//////////
//1.指定範圍替換
[str1 replaceCharactersInRange:NSMakeRange(2, 2) withString:@"123"];
NSLog(@"%@", str1);
//輸出: st123ng
//2.指定字串,條件,範圍替換
[str1 replaceOccurrencesOfString:@"123" withString:@"--" options:NSRegularExpressionSearch range:NSMakeRange(0, str1.length)];
NSLog(@"%@", str1);
//輸出: st--ng
複製程式碼
全部來自玩轉NSString