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

iOS 中的字串處理:NSString 與 NSMutableString

編輯:iOS 相關資訊

NSString 是 Objective-C 中用來處理文字的核心類別。本文系統整理字串的建立、轉換與常用操作。

建立字串物件

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"]; // 格式化初始化

也可以使用便利構造器完成字串拼接與 C/OC 字串轉換:

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

常用的 NSString 方法

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)

NSRange range1 = {4, 3};
NSString *ptr3 = [str5 substringWithRange:range1];            // 指定範圍擷取
NSString *ptr4 = [str5 substringWithRange:NSMakeRange(4, 3)]; // NSMakeRange 生成範圍

NSString *str = @"www.baidu.com";
BOOL ret = [str hasPrefix:@"www"];   // 判斷是否以指定字串開頭
NSString *str1 = @"1.txt";
BOOL ret1 = [str1 hasSuffix:@".txt"]; // 判斷是否以指定字串結尾

可變字串 NSMutableString

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"]; // 替換指定範圍
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved