您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS NSString 用法詳解:字串建立、轉換、分割與比較

編輯:iOS 相關資訊

NSString 是 iOS 開發中最常使用的類別之一。幾乎所有文字顯示、輸入輸出與資料格式化都會用到它。以下整理常見操作。

建立與格式化字串

NSString *text = [NSString stringWithFormat:@"The number is %d", number];

NSString 的操作通常不會改變自身,而是回傳新的字串。

長度與字元

NSUInteger length = text.length;
unichar character = [text characterAtIndex:0];

與 C 字串轉換

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 很豐富,但多數方法都會回傳新物件。理解這一點,可以避免誤以為原字串已經被修改。

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