作者:弦苦 授權本站轉載。
上一篇梳理了NSArray&NSMutableArray常用操作,這次來梳理一下Objective-C中每天都要用到的字符串處理類——NSString。
Objective-C中的NSString/NSMutableString類似MFC中的CString,封裝了字符串的日常基本操作。
1.創建初始化(Initialization&Creation)
1.1 常量字符串(literal string)
NSString*constString = @"Hello, World!";
變量constString並不是真正包含一個字符串對象,而指向內存中字符串對象的指針(地址),我們稱之為對象標識符。
以下示例中,字面量@“Hello, World!”存儲在文字常量區。指針constString1和constString2都指向它,它們在編譯時生成的真實類型是NSConstantString(繼承關系鏈——:NSSimpleCString:NSString)。
Objective-C裡沒有包或者命名空間,靠前綴來區分,NS是“NeXTSTEP”的縮寫。
CF是“CoreFoundation”的縮寫。CFString可以看做是NSString的C底層實現。
Foundation庫(Foundation.framework/Foundation.h)是有Cocoa框架提供的基本數據管理和服務功能的Objective-C接口,而Core Foundation庫 (CoreFoundation.framework/CoreFoundation.h) 則是Cocoa底層實現,提供了C語言層面的接口。
以下介紹不可變字符串兩種初始化創建方法。
After an immutable string has been initialized in the following way, it cannot be modified.
1.2 Initializing an String(NS_DESIGNATED_INITIALIZER)
- (instancetype)init NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_DESIGNATED_INITIALIZER; // 從UNICODE C String中選取定長字符初始化NSString對象 - (instancetype)initWithCharacters:(const unichar*)characters length:(NSUInteger)length; // 從UTF8 C String初始化NSString對象 - (instancetype)initWithUTF8String:(const char*)nullTerminatedCString; // 從C String初始化NSString對象,指定編碼格式。 - (instancetype)initWithCString:(const char*)nullTerminatedCString encoding:(NSStringEncoding)encoding; // 從另一個NSString初始化新的NSString對象 - (instancetype)initWithString:(NSString*)aString; // 從NSData指定編碼格式初始化NSString對象 - (instancetype)initWithData:(NSData*)data encoding:(NSStringEncoding)encoding; // 從C Buffer指定編碼格式初始化NSString對象 - (instancetype)initWithBytes:(const void*)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding; // 可變參格式化初始化NSString對象 - (instancetype)initWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
比較常用的有以下幾個:
// 從UTF8 C String初始化NSString對象 - (instancetype)initWithUTF8String:(constchar *)nullTerminatedCString; // 從C String初始化NSString對象,指定編碼格式(例如NSUTF8StringEncoding)。 - (instancetype)initWithCString:(constchar *)nullTerminatedCString encoding:(NSStringEncoding)encoding; // 從C Buffer指定編碼格式初始化NSString對象 - (instancetype)initWithBytes:(constvoid *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding; // 可變參格式化初始化NSString對象 - (instancetype)initWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
示例:
//NSString* string = [[NSString alloc] initWithFormat:@"Hello, %s","World!"]; NSString* string = [[NSString alloc] initWithFormat:@"Hello, %@", @"World!"]; NSLog(@"string= %@", string);
關於格式化規范,參考String Format Specifiers。
%@:OC對象描述(description)。
%d/%D:帶符號32位整數(int),NSInteger:%ld,size_t:%zd。
%u/%U:無符號32位整數(unsigned int),NSUInteger:%lu。
%o/%O:無符號32位整數(unsigned int)的八進制格式。
%x/%X:無符號32位整數(unsigned int)的十六進制格式。
%c:8位無符號字符(unsigned char)。如果非ASCII碼則以八進制“\\ddd”或十六進制“\\udddd”格式顯示字符值。
%C:16位UNICODE字符(unichar)。如果非ASCII碼則以八進制“\\ddd”或十六進制“\\udddd”格式顯示字符值。
%f:64位浮點數(double)
1.3 Creating an String(autorelease)
// 創建一個字符串獨享,其值為空 + (instancetype)string;
示例:
NSString* constString = @""; NSString* string = [NSString string]; BOOL bPointerEqual = constString==string; // NO BOOL bContentEqualTo = [constString isEqualTo:string]; // YES BOOLbEqualToString = [constString isEqualToString:string]; // YES 以下是一些便利構造方法:
// initWithString對應的類方法 + (instancetype)stringWithString:(NSString *)string; // initWithCString:encoding對應的類方法 + (instancetype)stringWithCString:(const charchar *)cString encoding:(NSStringEncoding)enc; // initWithCharacters:length: 對應的類方法 + (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length; // initWithUTF8String對應的類方法 + (instancetype)stringWithUTF8String:(const charchar *)nullTerminatedCString; // initWithFormat對應的類方法 + (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + (instancetype)localizedStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
比較常用的有以下幾個:
// initWithCString:encoding對應的類方法 + (instancetype)stringWithCString:(constchar *)cString encoding:(NSStringEncoding)enc; // initWithUTF8String對應的類方法 + (instancetype)stringWithUTF8String:(constchar *)nullTerminatedCString; // initWithFormat對應的類方法 + (instancetype)stringWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
2.訪問字符串(Querying)
2.1 字符串長度(字符數組大小)
// Thenumber of Unicode characters in the receiver. @property (readonly) NSUInteger length;
示例:
NSString* constString1 = nil; NSString* constString2 = @""; NSString* constString3 = @"Hello, World!"; NSString* constString4 = @"哈喽,世界!"; // 漢字+半角標點混合 NSLog(@"constString1[size,length] = [%zd, %zd]", sizeof(constString1),constString1.length); // [8,0] NSLog(@"constString2[size,length] = [%zd, %zd]", sizeof(constString2),constString2.length); // [8,0] NSLog(@"constString3[size,length] = [%zd, %zd]", sizeof(constString3),constString3.length); // [8,13] NSLog(@"constString4[size,length] = [%zd, %zd]", sizeof(constString4),constString4.length); // [8,6]
以上可知string.length可用來判空:如果length為零,則表示字符串對象為nil或為不包含任何字符。
2.2 字符(字符數組元素)
// 獲取指定索引位置/范圍的字符(集) - (unichar)characterAtIndex:(NSUInteger)index; - (void)getCharacters:(unichar *)buffer range:(NSRange)aRange;
示例:
unichar ch = [constString3 characterAtIndex:7]; NSLog(@"ch = %c", ch); // W unichar* cBuf = malloc(sizeof(unichar)*constString3.length); [constString3 getCharacters:cBuf]; NSString* stringFromCharacters1 = [[NSString alloc] initWithCharacters:cBuf length:constString3.length]; NSLog(@"stringFromCharacters1 = %@", stringFromCharacters1); // @"Hello, World!" [stringFromCharacters1 release]; [constString3 getCharacters:cBuf range:NSMakeRange(7, 6)]; NSString* stringFromCharacters2 = [NSString stringWithCharacters:cBuf length:constString3.length]; NSLog(@"stringFromCharacters2 = %@", stringFromCharacters2); // @"World! World!"
2.3 取C String
//Convenience to return null-terminated UTF8 representation @property (readonly) __strong const charchar *UTF8String NS_RETURNS_INNER_POINTER;
2.4 取字面值
類似cstdlib中的atoi/atol/strtol/atof。
/* convenience methods all skip initial space characters (whitespaceSet)and ignore trailing characters. NSScanner can be used for more"exact" parsing of numbers. */ @property (readonly) double doubleValue; @property (readonly) float floatValue; @property (readonly) int intValue; @property (readonly) NSInteger integerValue NS_AVAILABLE(10_5, 2_0); @property (readonly) long long longLongValue NS_AVAILABLE(10_5, 2_0); @property (readonly) BOOL boolValue NS_AVAILABLE(10_5, 2_0);
2.5 大小寫轉換
// 所有字符轉換成大寫 @property (readonly, copy) NSString *uppercaseString; // 所有字符轉換成小寫 @property (readonly, copy) NSString *lowercaseString; // 每個單詞首字母大寫,其余字母小寫。 @property (readonly, copy) NSString *capitalizedString;
3.查詢字符串(Finding)
3.1 查詢子串
// 返回查找到包含子串的范圍 - (NSRange)rangeOfString:(NSString *)aString; // 返回查找到包含子串的范圍,可指定查詢選項(忽略大小寫、逆序) - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask; // 返回查找到包含子串的范圍,可指定查詢選項(忽略大小寫、逆序),可進一步指定查找范圍 - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
3.2 取子串
// 返回從指定索引到結尾的子串 - (NSString *)substringFromIndex:(NSUInteger)from; // 返回從開頭到指定索引的子串 - (NSString *)substringToIndex:(NSUInteger)to; // 返回從指定范圍(開始索引+長度)界定的子串 - (NSString *)substringWithRange:(NSRange)range; // Hint: Use withrangeOfComposedCharacterSequencesForRange: to avoid breaking up composedcharacters
示例:
NSString* prefix = [constString3 substringToIndex:7]; // @"Hello, " NSString* suffix = [constString3 substringFromIndex:7]; // @"World!" NSString* substr =[constString3 substringWithRange:NSMakeRange(3,6)]; // @"lo, Wo"
3.3 是否包含子串
// 是否以指定子串開頭 - (BOOL)hasPrefix:(NSString *)aString; // 是否以指定子串結尾 - (BOOL)hasSuffix:(NSString *)aString; // 是否包含子串,注意只適用於iOS8以上! - (BOOL)containsString:(NSString *)aString NS_AVAILABLE(10_10, 8_0);
示例:
BOOL bHasPrefix = [constString3 hasPrefix:@"Hello,"]; // YES BOOL bHasSuffix = [constString3 hasSuffix:@"World!"]; // YES BOOL bContain= [constString3 containsString:@"lo, Wo"]; // YES
以下為NSString擴展類別(Category)判斷是否包含子串的適配接口:
- (BOOL)hasContainStr:(NSString*)subStr { if(!subStr) { return NO; } if([self respondsToSelector:@selector(containsString:)]) { // ≥iOS8 return [self containsString:subStr]; } else { //0 ? YES : NO); } }
3.4 查詢字符集
/* These return the range of the first character from the set in thestring, not the range of a sequence of characters. */ - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange; - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index; - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range NS_AVAILABLE(10_5, 2_0);
4.比較字符串(Comparing)
// 判斷兩個字符串內容是否相等 - (BOOL)isEqualToString:(NSString *)aString; /* In the compare: methods, the range argument specifies the subrange,rather than the whole, of the receiver to use in the comparison. The range is not applied to the search string. For example, [@"AB"compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares"A" to "ABC", not "A" to "A", and will return NSOrderedAscending. */ // 比較字符串,如果相同返回NSOrderedSame;如果不相同,返回第一個不相同的字符值比較結果(NSOrderedAscending、NSOrderedDescending) - (NSComparisonResult)compare:(NSString *)string; // 比較字符串,可指定比較選項(忽略大小寫、逆序、按十進制值) - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; // 比較字符串,可指定比較選項(忽略大小寫、逆序、按十進制值),可進一步指定查找范圍 - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange; // 比較字符串,可指定查詢選項(忽略大小寫、逆序、按十進制值),可進一步指定查找范圍,可進一步按照本地化比較 - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange locale:(id)locale; //locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice. // 相當於compare:string options:NSCaseInsensitiveSearch - (NSComparisonResult)caseInsensitiveCompare:(NSString *)string; // 按照本地化比較 - (NSComparisonResult)localizedCompare:(NSString *)string; // 以上兩個版本組合 - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
5.替換子串(Replacing)
/* Replace all occurrences of the target string in the specified range with replacement. Specified compare options are used for matching target. IfNSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch.*/ - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange NS_AVAILABLE(10_5, 2_0); /* Replace all occurrences of the target string with replacement. Invokes the above method with 0 options and range of the whole string.*/ - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0); /* Replace characters in range with the specified string, returning new string.*/ - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0);
6.衍生字符串(Deriving)
// 當前字符串追加aString生成返回一個新的NSString對象。 - (NSString *)stringByAppendingString:(NSString *)aString; - (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
7.拆分字符串(Separate & Join Components)
// NSString::componentsSeparatedByString接口按照分割字符(子串)來切分字符串:NSString->NSArray - (NSArray *)componentsSeparatedByString:(NSString *)separator; - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0); // NSArray::componentsJoinedByString接口將多個字符串(字符串數組)以銜接字符連接:NSArray->NSString - (NSString *)componentsJoinedByString:(NSString *)separator;
以下代碼示例將字符串按分隔符拆分,然後按分隔符銜接復原:
NSString* originString = @"do-do-sol-sol-la-la-sol"; NSArray* components = [originString componentsSeparatedByString:@"-"]; // 拆分 NSLog(@"components = %@", components); NSString* recoverString = [components componentsJoinedByString:@"-"]; //復原 NSLog(@"recoverString = %@", recoverString);
8.可變字符串(NSMutableString)
8.1 Initializing an String(NS_DESIGNATED_INITIALIZER)
/* In addition to these two, NSMutableString responds properly to allNSString creation methods.*/ - (NSMutableString *)initWithCapacity:(NSUInteger)capacity; + (NSMutableString *)stringWithCapacity:(NSUInteger)capacity;
8.2 set/append aString
// Replaces the characters of the receiver with those in a given string.aString must not be nil. - (void)setString:(NSString *)aString;
setString類似於對retain propery的賦值(setter)。
字符串置為空串:=@””或setString:@””;
// Adds to the end of the receiver the characters of a given string.aString must not be nil - (void)appendString:(NSString *)aString; - (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
8.3 insert/replace
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc; // 替換 - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString; - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
8.4 delete
// 刪除指定位置、指定長度的子串 - (void)deleteCharactersInRange:(NSRange)range;
9.文件、URL與字符串
9.1 從指定文件讀取內容到字符串
- (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; + (instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
9.2 從指定url讀取(下載)內容到字符串
- (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; + (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
9.3 將字符串內容寫到指定url/path
/* Write to specified url or path using the specified encoding.*/ - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFileencoding:(NSStringEncoding)encerror:(NSError **)error; - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFileencoding:(NSStringEncoding)encerror:(NSError **)error;
10.字符串化
10.1 NSString & Class
// 獲取某個對象的具體類名,傳入[obj class],相當於[objclassName] FOUNDATION_EXPORT NSString *NSStringFromClass(Class aClass); // 基於類名獲取類 FOUNDATION_EXPORT Class NSClassFromString(NSString *aClassName);
示例:
NSLog(@"[constString2 className] = %@", [constString2 className]); // __NSCFConstantString NSLog(@"NSStringFromClass([constString2 class]) = %@", NSStringFromClass([constString2class])); //__NSCFConstantString NSLog(@"object_getClassName(constString2) = %s", object_getClassName(constString2));// __NSCFConstantString // 返回C字符串格式的類名 const char* className = class_getName([obj class]);
10.2 NSString & SEL
類似的還有NSStringFromSelector/NSSelectorFromString。
Class _alertManager = NSClassFromString([NSString stringWithFormat:@"_UIAlertManager"]); SEL methodSel = NSSelectorFromString([NSStringstringWithFormat:@"topMostAlert"]); if ([_alertManager respondsToSelector:methodSel]) { id topView = objc_msgSend(_alertManager, methodSel); }
10.3 NSString & CGPoint/CGSize/CGRect
NSStringFromCGPoint/CGPointFromString、NSStringFromCGSize/CGSizeFromString、 NSStringFromCGRect/CGRectFromString。
參考:
《NSString &Unicode》
《遍歷NSString每一個字符的正確方式》
《NSString屬性用copy還是用strong?》
《Use copy for NSStringproperties》
《NSString: isEqual vs.isEqualToString》
《Equality》《isEqual: vsisEqualToString:》
《Objective-c中 isEqual ,isEqualToString , == 三者的區別》
《How to convert anNSString to hex values》
《NSString轉換成16進制》《Objective-C NSStringto Hex》
《How to convertNSString to hexadecimal string of fixed block size》
版權聲明:本文為博主原創文章,未經博主允許不得轉載。