如果說 NSObject 是所有類的起點,那麼 NSString 大概是被使用得最頻繁的那一個。從網路回應到本地檔案、從使用者輸入到 API 參數,字串幾乎滲透在每一行程式碼裡。以下依功能把 NSString 的能力盤點一遍。
NSObjectNSCopying、NSMutableCopying、NSSecureCodingNSString.h、NSPathUtilities.h、NSlinguisticTagger.h、NSURL.h便利建構子包括 +string、+stringWithString:、+stringWithCharacters:length:、+stringWithFormat:、+localizedStringWithFormat:。從位元資料出發則有 -initWithBytes:length:encoding:、-initWithBytesNoCopy:length:encoding:freeWhenDone:、-initWithData:encoding:、-initWithUTF8String:、-initWithCString:encoding:。格式化系列還細分為 -initWithFormat:arguments:、-initWithFormat:locale:、-initWithFormat:locale:arguments: 等多種變化。
早期那批不帶 encoding 的 C 字串方法(+stringWithCString:、-initWithCString: 等)早在 iOS 2.0 就已淘汰,因為它們無法處理非 ASCII 內容。
+stringWithContentsOfFile:encoding:error:、+stringWithContentsOfFile:usedEncoding:error: 以及對應的 URL 版本,能自動偵測或明確指定編碼。第二組的 usedEncoding 會回傳實際採用(或偵測到)的編碼,處理來源不明的文字檔時特別有用。
-writeToFile:atomically:encoding:error: 與 -writeToURL:atomically:encoding:error: 是現代做法;不帶 encoding 的舊版本已在 iOS 2.0 淘汰。
-length 回傳的是 UTF-16 碼元數量,並非「使用者看到的字數」;-lengthOfBytesUsingEncoding: 才是編碼後的位元組數,-maximumLengthOfBytesUsingEncoding: 則用來預估緩衝區大小。
-characterAtIndex:、-getCharacters:range:、-getBytes:maxLength:usedLength:encoding:options:range:remainingRange: 構成底層存取介面。
-cStringUsingEncoding:、-getCString:maxLength:encoding:、-UTF8String 是 interop 的三件套。注意 -UTF8String 回傳的指標,其生命週期與 autorelease pool 綁定,若需長期保留務必自行複製。
拼接:-stringByAppendingFormat:、-stringByAppendingString:、-stringByPaddingToLength:withString:startingAtIndex:。
拆分:-componentsSeparatedByString:、-componentsSeparatedByCharactersInSet:、-stringByTrimmingCharactersInSet:、-substringFromIndex:、-substringToIndex:、-substringWithRange:。
-rangeOfString: 系列可搭配 NSCaseInsensitiveSearch、NSLiteralSearch、NSBackwardsSearch、NSAnchoredSearch 等遮罩;-rangeOfCharacterFromSet: 系列則以字元集為搜尋依據。若要依地區規則比對,-rangeOfString:options:range:locale: 是最佳選擇。逐行或逐段處理則用 -enumerateLinesUsingBlock: 與 -enumerateSubstringsInRange:options:usingBlock:。
-stringByReplacingOccurrencesOfString:withString:(含 options:range: 版本)與 -stringByReplacingCharactersInRange:withString: 涵蓋絕大多數替換需求。
-getLineStart:end:contentsEnd:forRange:、-lineRangeForRange:、-getParagraphStart:end:contentsEnd:forRange:、-paragraphRangeForRange: 讓你能精確切出行與段落的邊界,是文字編輯器的基礎工具。
某些字元(如組合附加符號、emoji)由多個碼元構成。-rangeOfComposedCharacterSequenceAtIndex: 與 -rangeOfComposedCharacterSequencesForRange: 能確保你不會把一個完整字元切成兩半。
-propertyList 與 -propertyListFromStringsFileFormat 可把字串直接解析為物件,是讀取 .strings 資源檔的捷徑。
從嚴格相等到依地區排序:-isEqualToString:、-caseInsensitiveCompare:、-localizedCaseInsensitiveCompare:、-compare:、-localizedCompare:、-compare:options:、-compare:options:range:、-compare:options:range:locale:、-localizedStandardCompare:(最貼近使用者直覺的排序方式,適合檔案清單)、-hasPrefix:、-hasSuffix: 與 -hash。
-stringByFoldingWithOptions:locale: 可移除附加符號,讓搜尋忽略重音;-commonPrefixWithString:options: 找出共同開頭;大小寫轉換有 -capitalizedString、-lowercaseString、-uppercaseString 及各自的 ...WithLocale: 版本(土耳其語的 i 問題就靠它解決)。
-decomposedStringWithCanonicalMapping、-decomposedStringWithCompatibilityMapping、-precomposedStringWithCanonicalMapping、-precomposedStringWithCompatibilityMapping 處理 Unicode 的分解與組合形式,跨平台比對文字時常是關鍵。
-intValue、-integerValue、-longLongValue、-floatValue、-doubleValue、-boolValue 提供寬鬆的字串轉數字能力。要嚴格解析請改用 NSScanner。
+availableStringEncodings、+defaultCStringEncoding、+localizedNameOfStringEncoding:、-canBeConvertedToEncoding:、-dataUsingEncoding:、-dataUsingEncoding:allowLossyConversion:、-fastestEncoding、-smallestEncoding 組成完整的編碼工具箱。
+pathWithComponents:、-pathComponents、-lastPathComponent、-pathExtension、-stringByAppendingPathComponent:、-stringByAppendingPathExtension:、-stringByDeletingLastPathComponent、-stringByDeletingPathExtension、-isAbsolutePath、-stringByStandardizingPath、-stringByExpandingTildeInPath、-stringByAbbreviatingWithTildeInPath、-stringByResolvingSymlinksInPath、-completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:、-fileSystemRepresentation、-getFileSystemRepresentation:maxLength:、-stringsByAppendingPaths:。
實務提醒:字串拼接路徑容易在邊界情況出錯, iOS 16 之後更推薦使用 NSURL 的 appendingPathComponent:。
-stringByAddingPercentEscapesUsingEncoding:、-stringByReplacingPercentEscapesUsingEncoding:、-stringByAddingPercentEncodingWithAllowedCharacters:、-stringByRemovingPercentEncoding。其中 stringByAddingPercentEncodingWithAllowedCharacters: 搭配 NSCharacterSet URLQueryAllowedCharacterSet 是處理查詢參數的正確姿勢。
-enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock: 與 -linguisticTagsInRange:scheme:options:orthography:tokenRanges: 能辨識詞性、語言、拼寫等資訊,是實作進階文字功能的起點。
這個類別的 API 表面看似雜亂,其實有清晰的層次:建立 → 存取 → 轉換 → 比對 → 分析。掌握這條主線,再回頭查手冊就會快得多。
資料來源:Apple Inc. NSString Class Reference(更新日期 2014-02-11)