NSString 是 iOS 開發中最常使用的類別之一。幾乎所有文字顯示、輸入輸出與資料格式化都會用到它。以下整理常見操作。
NSString *text = [NSString stringWithFormat:@"The number is %d", number];
NSString 的操作通常不會改變自身,而是回傳新的字串。
NSUInteger length = text.length;
unichar character = [text characterAtIndex:0];
const char *cString = [text UTF8String];
NSString *newString = [NSString stringWithUTF8String:cString];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.txt"];
[text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:error];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:error];
NSArray *words = [text componentsSeparatedByString:@" "];
NSString *prefix = [text substringToIndex:3];
NSString *suffix = [text substringFromIndex:4];
NSString *middle = [text substringWithRange:range];
NSRange range = [text rangeOfString:@"is"];
NSString *replaced = [text stringByReplacingOccurrencesOfString:@" " withString:@"*"];
NSString *upper = [text uppercaseString];
NSString *lower = [text lowercaseString];
BOOL equal = [text isEqualToString:otherText];
BOOL hasPrefix = [text hasPrefix:@"Hello"];
BOOL hasSuffix = [text hasSuffix:@"d!"];
NSInteger intValue = [text intValue];
float floatValue = [text floatValue];
double doubleValue = [text doubleValue];
NSString 的 API 很豐富,但多數方法都會回傳新物件。理解這一點,可以避免誤以為原字串已經被修改。