您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

NSString 類別全解:Foundation 字串處理的完整地圖

編輯:iOS 開發綜合

如果說 NSObject 是所有類的起點,那麼 NSString 大概是被使用得最頻繁的那一個。從網路回應到本地檔案、從使用者輸入到 API 參數,字串幾乎滲透在每一行程式碼裡。以下依功能把 NSString 的能力盤點一遍。

類別關係與基本資訊

  • 繼承:NSObject
  • 遵循協議:NSCopying、NSMutableCopying、NSSecureCoding
  • 所屬框架:Foundation(iOS 2.0 及以後)
  • 常見宣告位置:NSString.h、NSPathUtilities.h、NSlinguisticTagger.h、NSURL.h
  • 配套指南:《String Programming Guide》《Property List Programming Guide》

建立與初始化

便利建構子包括 +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 內容。

從檔案與 URL 讀入

+stringWithContentsOfFile:encoding:error:、+stringWithContentsOfFile:usedEncoding:error: 以及對應的 URL 版本,能自動偵測或明確指定編碼。第二組的 usedEncoding 會回傳實際採用(或偵測到)的編碼,處理來源不明的文字檔時特別有用。

寫入檔案與 URL

-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: 構成底層存取介面。

取得 C 字串

-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:。

URL 相關

-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)

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved