NSString 是 Objective-C 中處理字符串的核心類,掌握它的創建、轉換與常用方法,是 iOS 開發的基本功。以下做系統性整理。
NSString *str1 = @"hello world"; NSString *str = [[NSString alloc] initWithString:@"hello world!"]; NSString *str_1 = [[NSString alloc] initWithUTF8String:"hello world"]; // 把 C 字符串轉為 OC 字符串 int a = 123; NSString *str_3 = [[NSString alloc] initWithFormat:@"a = %d %s%@", a, "abcd", @"efg"]; // 格式化字符串初始化 // 便利構造器 NSString *str1 = [NSString stringWithString:@"hello world"]; NSString *str2 = [NSString stringWithUTF8String:"hello world"]; NSString *str3 = [NSString stringWithFormat:@"%s", "hello world"];
NSString *str = @"hello"; const char *p = [str UTF8String]; // OC 字符串轉為 C 字符串 str = @"123"; int a = [str intValue]; // 數字串轉為整型 [str floatValue]; // 數字串轉為 float [str doubleValue]; // 數字串轉為 double
NSLog(@"%ld", [str1 length]); // 求字符串長度
NSLog(@"%c", [str1 characterAtIndex:1]); // 獲取指定位置的字符
BOOL ret = [str1 isEqualTo:str2]; // 比較是否相等
long ret1 = [str1 compare:str2]; // 比較大小:大返回 1,等返回 0,小返回 -1
long ret2 = [str1 caseInsensitiveCompare:str2]; // 不區分大小寫比較
NSString *ptr = [str2 uppercaseString]; // 全部轉大寫(不改變原串)
ptr = [str1 lowercaseString]; // 全部轉小寫
ptr = [str3 capitalizedString]; // 首字母大寫,其餘小寫
// 查找子串
NSString *str4 = @"hello world";
NSRange range = [str4 rangeOfString:@"wr"]; // 找不到返回 NSNotFound
if (range.location != NSNotFound) {
NSLog(@"%ld %ld", range.location, range.length);
}
// 字符串抽取
NSString *str5 = @"helloworld";
NSString *ptr1 = [str5 substringToIndex:4]; // 從 0 到 4(不含 4)
NSString *ptr2 = [str5 substringFromIndex:5]; // 從 5 到結尾(含 5)
NSString *ptr3 = [str5 substringWithRange:NSMakeRange(4, 3)]; // 指定範圍抽取
// 判斷前綴與後綴
NSString *str = @"www.baidu.com";
BOOL ret = [str hasPrefix:@"www"]; // 是否以指定字符串開頭
NSString *str1 = @"1.txt";
BOOL ret1 = [str1 hasSuffix:@".txt"]; // 是否以指定字符串結尾
NSMutableString 繼承自 NSString,可以使用 NSString 的所有方法,同時支援動態增刪內容:
NSMutableString *str = [[NSMutableString alloc] initWithString:@"hello"]; [str insertString:@"123" atIndex:1]; // 在指定下標插入 [str appendString:@"123"]; // 末尾追加 [str deleteCharactersInRange:NSMakeRange(0, 2)]; // 刪除指定範圍字符 [str setString:@"baidu"]; // 修改(賦值) [str replaceCharactersInRange:NSMakeRange(3, 1) withString:@"ios"]; // 替換指定範圍
要注意的是,使用 insertString:atIndex: 等方法時需留意下標不要越界,否則會引發崩潰。