字符串處理是 iOS 開發最高頻的操作之一。本文系統整理 NSString (不可變) 與 NSMutableString (可變) 的創建、讀寫檔案、比較、大小寫轉換、搜尋、子串擷取、路徑操作、格式化、容量管理、增刪改查等核心 API,附帶完整代碼範例,作為開發速查手冊。
// 1. 常量字符串 (編譯期確定,駐留區,無需釋放)
NSString *str1 = @"This is a String!";
// 2. alloc/init + 賦值 (手動管理記憶體,MRC 時代)
NSString *str2 = [[NSString alloc] init];
str2 = @"This is a String!"; // 注意:這裡直接賦值常量,原 init 物件洩漏
[str2 release];
// 3. initWithString: (高效複製現有字符串)
NSString *str3 = [[NSString alloc] initWithString:@"This is a String!"];
// 4. initWithCString:encoding: (從 C 字符串創建)
char *cStr = "This is a String!";
NSString *str4 = [[NSString alloc] initWithCString:cStr encoding:NSUTF8StringEncoding];
// 5. 格式化字符串 (類 printf)
int i = 1, j = 2;
NSString *str5 = [[NSString alloc] initWithFormat:@"%d. This is %d string!", i, j];
// 6. 便利構造器 (自動釋放池,ARC 下無需釋放)
NSString *str6 = [NSString stringWithCString:"temporary" encoding:NSUTF8StringEncoding];
NSString *str7 = [NSString stringWithFormat:@"Item %d", index];
// 讀取檔案內容為字符串
NSString *path = @"/path/to/file.txt";
NSString *content = [[NSString alloc] initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
// 寫入字符串到檔案
NSString *content = @"Hello World";
[content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
// atomically:YES 先寫臨時檔再重命名,保證寫入原子性
NSString *s1 = @"Hello";
NSString *s2 = @"hello";
NSString *s3 = @"Hello";
// 完全相等 (區分大小寫)
BOOL eq1 = [s1 isEqualToString:s3]; // YES
// 不區分大小寫比較
BOOL eq2 = [s1 caseInsensitiveCompare:s2] == NSOrderedSame; // YES
// 標準比較 (按字典序)
NSComparisonResult cmp = [s1 compare:s2]; // NSOrderedDescending (s1 > s2)
NSComparisonResult cmp2 = [s1 compare:s2 options:NSCaseInsensitiveSearch]; // NSOrderedSame
// 選項說明
// NSCaseInsensitiveSearch: 忽略大小寫
// NSLiteralSearch: 逐字元精確比較 (預設)
// NSNumericSearch: 數字感知比較 (如 "file2" < "file10")
// NSDiacriticInsensitiveSearch: 忽略發音符號
// NSWidthInsensitiveSearch: 忽略全半形差異
// NSForcedOrderingSearch: 強制排序 (無明確順序時)
NSString *s = @"Hello World";
NSLog(@"uppercase: %@", [s uppercaseString]); // HELLO WORLD
NSLog(@"lowercase: %@", [s lowercaseString]); // hello world
NSLog(@"capitalized: %@", [s capitalizedString]); // Hello World (每詞首字母大寫)
// 當地化版本:uppercaseStringWithLocale: 等
NSString *haystack = @"This is a string";
NSString *needle = @"string";
NSRange range = [haystack rangeOfString:needle];
if (range.location != NSNotFound) {
NSLog(@"找到於位置 %lu, 長度 %lu", range.location, range.length);
}
// 進階搜尋選項
NSRange r = [haystack rangeOfString:needle
options:NSCaseInsensitiveSearch | NSBackwardsSearch
range:NSMakeRange(0, 10)];
NSString *s = @"This is a string";
// 從開頭到指定索引 (不含該索引字元)
NSString *sub1 = [s substringToIndex:4]; // "This"
// 從指定索引到結尾 (含該索引字元)
NSString *sub2 = [s substringFromIndex:5]; // "is a string"
// 指定範圍
NSString *sub3 = [s substringWithRange:NSMakeRange(5, 2)]; // "is"
NSString *path = @"~/Documents/data.txt";
// 擴展波浪號 (~ → 家目錄)
NSString *absPath = [path stringByExpandingTildeInPath]; // /Users/name/Documents/data.txt
// 縮短路徑 (家目錄 → ~)
NSString *shortPath = [absPath stringByAbbreviatingWithTildeInPath]; // ~/Documents/data.txt
// 取得副檔名
NSString *ext = [path pathExtension]; // "txt"
// 刪除副檔名
NSString *noExt = [path stringByDeletingPathExtension]; // "~/Documents/data"
// 取得最後路徑分量
NSString *last = [path lastPathComponent]; // "data.txt"
// 刪除最後分量
NSString *dir = [path stringByDeletingLastPathComponent]; // "~/Documents"
// 追加路徑分量
NSString *newPath = [dir stringByAppendingPathComponent:@"new.txt"]; // "~/Documents/new.txt"
// 指定初始容量 (避免頻繁擴容)
NSMutableString *mstr = [NSMutableString stringWithCapacity:100];
// 或
NSMutableString *mstr = [[NSMutableString alloc] initWithCapacity:100];
NSMutableString *mstr = [NSMutableString stringWithString:@"Hello"];
[mstr appendString:@", World!"]; // 追加字符串
[mstr appendFormat:@" Number: %d", 42]; // 格式化追加
// 結果: "Hello, World! Number: 42"
[mstr deleteCharactersInRange:NSMakeRange(0, 5)]; // 刪除 "Hello"
// 結果: ", World! Number: 42"
[mstr insertString:@"Hi! " atIndex:0];
// 結果: "Hi! , World! Number: 42"
[mstr setString:@"Brand New Content"];
[mstr replaceCharactersInRange:NSMakeRange(0, 4) withString:@"Hey"];
// NSMutableString → NSString (無拷貝開銷,單純類型轉換)
NSString *immutable = [mutableString copy]; // 或直接賦值給 NSString *
// NSString → NSMutableString
NSMutableString *mutable = [immutableString mutableCopy];
NSMutableString 或 [NSArray componentsJoinedByString:],避免循環 stringByAppendingString: 產生大量中間對象[NSString stringWithFormat:] 方便但有解析開銷,熱路徑考慮手動拼接NSUTF8StringEncoding,避免亂碼@"..." 語法,編譯期常量、全局唯一、零開銷NSLocalizedString(@"key", @"comment")NSRegularExpression (iOS 4+) 處理複雜模式匹配/替換/擷取initWithCString: 不指定 encoding → 預設 ASCII,中文亂碼stringWithContentsOfFile: 不檢查 error → 靜默失敗返回 nilrangeOfString: 未判斷 NSNotFound 直接用 location → 崩潰/邏輯錯誤NSMutableString 時持有者未同步更新 (如作為 Dictionary Key) → 雜湊表失效