NSString 是 iOS 開發中使用頻率最高的類別之一。這篇把幾個容易混淆的基礎知識整理清楚:NSRange 的意義、常見的幾何結構、字串的比較與查找,以及可變字串的操作。
NSRange 的結構如下:
typedef struct _NSRange {
unsigned int location; // 起始位置
unsigned int length; // 該範圍內所含元素個數
} NSRange;
以字串 "Objective-C is a cool language" 為例,單字 "cool" 可以用 location = 17、length = 4 的範圍來表示。
要注意的是,如果 location 欄位未被初始化,它的值可能是 NSNotFound,用來表示一個無意義的範圍。實務上這點很重要:當 rangeOfString: 找不到目標時,回傳的範圍 location 就是 NSNotFound,直接拿去做 substringWithRange: 會 crash。
建立 NSRange 有三種方式:
// 1. 直接指定欄位
NSRange range;
range.location = 17;
range.length = 4;
// 2. 使用 C 的聚合結構賦值
NSRange range = {17, 4};
// 3. 使用 Cocoa 提供的便捷函式
NSRange range = NSMakeRange(17, 4);
typedef struct _NSPoint {
float x;
float y;
} NSPoint;
typedef struct _NSSize {
float width;
float height;
} NSSize;
typedef struct _NSRect {
NSPoint origin;
NSSize size;
} NSRect;
同樣有對應的便捷函式:NSMakePoint()、NSMakeSize()、NSMakeRect()。
除了直接賦值,還可以用 stringWithFormat: 依格式字串與參數產生字串:
NSString *height; height = [NSString stringWithFormat:@"Your height is %d feet, %d inches", 5, 11]; // 結果:"Your height is 5 feet, 11 inches"
這個方法有兩個細節:後面的省略號代表可接受多個以逗號分隔的參數;方法宣告開頭是 + 號,代表它是類別方法(又稱工廠方法)。
取得長度:
unsigned int length = [height length];
這個方法能正確處理國際字元集,包含中文、日文、俄文等。
NSString *thing1 = @"hello 2";
NSString *thing2 = [NSString stringWithFormat:@"hello %d", 5];
if ([thing1 isEqualToString:thing2])
{
NSLog(@"They are the same!");
}
關鍵區別:isEqualToString: 比較的是字串內容,而 == 比較的是指標位址。兩個內容相同的字串,指標不見得相同,因此永遠用 isEqualToString: 來比對字串。
typedef enum _NSComparisonResult {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
} NSComparisonResult;
例如 [@"zoinks" compare:@"jinies"] 會回傳 NSOrderedDescending,代表左側字串排在右側之後。
options 是位掩碼參數,可用位元或運算子組合多個選項:
if ([thing1 compare:thing2 options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame)
{
NSLog(@"They match!");
}
// 是否以某字串開頭 - (BOOL)hasPrefix:(NSString *)aString; // 是否以某字串結尾 - (BOOL)hasSuffix:(NSString *)aString; // 找出子字串的範圍 - (NSRange)rangeOfString:(NSString *)aString;
範例:
NSString *fileName = @"draft-chapter.pages"; NSRange range = [fileName rangeOfString:@"chapter"]; // range.location = 6, range.length = 7 // 若找不到,range.location 會等於 NSNotFound
NSString 是不可變的,但這不代表你不能操作它——Cocoa 提供了子類 NSMutableString。
// 建立時可指定建議容量(僅為效能上的建議,非上限) NSMutableString *string = [NSMutableString stringWithCapacity:42];
常用操作:
// 附加字串 [string appendString:@"Hello there"]; // 附加格式化字串 [string appendFormat:@"human %d!", 39]; // 刪除指定範圍 - (void)deleteCharactersInRange:(NSRange)range;
deleteCharactersInRange: 常與 rangeOfString: 搭配使用:
NSMutableString *friends = [NSMutableString stringWithCapacity:50]; [friends appendString:@"James BethLynn Jack Evan"]; NSRange jackRange = [friends rangeOfString:@"Jack"]; jackRange.length++; // 把後面那個空格也一起刪掉 [friends deleteCharactersInRange:jackRange]; // 結果:"James BethLynn Evan"
兩個最容易出事的地方:一是 rangeOfString: 找不到時回傳 NSNotFound,務必在使用前檢查;二是 NSMutableString 的 replaceCharactersInRange:withString: 若新字串長度與原範圍不同,後續快取的位置資訊(例如已算好的 NSRange)就會失效,需要重新計算。