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

中文字元與 NSString 的編碼轉換陷阱

編輯:iOS 相關資訊

在 Xcode 中,檔案以 UTF-8 格式保存,其中的變數與物件也同樣以 UTF-8 編碼存放。不同語言的 UTF-8 編碼並不相同,英文的 UTF-8 編碼剛好與 ASCII 碼一致。

由於每個字元的 UTF-8 編碼位元組數不同,取編碼的方式也有所差異。對英文字元而言,取出字元即等同於它的 ASCII 碼;其實對非英文字元,取字元集編碼的方式也一樣,只是統稱為「取 ASCII 碼」。

網路上常見的範例多半只示範如何讓英文字元與 ASCII 碼互轉,卻沒提到中文等非英文處理,用同樣方式就會得到亂碼。先看英文的寫法:

// NSString 轉 ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65

// ASCII 轉 NSString
int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A

若換成中文測試,用 [NSString stringWithFormat:@"%c", asciiCode] 得到的會是亂碼,代表根本沒有正確辨識。

在說明解法前,先來看 string​WithFormat 的兩種相關格式:

%c:8 位元 unsigned char,以 ASCII 字元輸出;若非 ASCII 字元,則以八或十六進位表示。

%C:16 位元 Unicode 字元(unichar),可正確輸出非 ASCII 字元。

因此,改用 [NSString stringWithFormat:@"%C", asciiCode] 就能正確取得中文、日文等字元。以下分別以英文、中文、日文舉例:

NSString *theString = @"g";
unichar theChar = [theString characterAtIndex:0];
NSString *theString1 = [NSString stringWithFormat:@"%c", theChar];
NSString *theString2 = [NSString stringWithFormat:@"%C", theChar];
NSLog(@"theString=%@,%d,%@,%@", theString, theChar, theString1, theString2);

theString = @"家";
theChar = [theString characterAtIndex:0];
theString1 = [NSString stringWithFormat:@"%c", theChar];
theString2 = [NSString stringWithFormat:@"%C", theChar];
NSLog(@"theString=%@,%d,%@,%@", theString, theChar, theString1, theString2);

輸出結果如下:

theString=g,103,g,g
theString=家,23478,?,家

可以看到,%C 能正確還原中文,而 %c 則顯示為問號。這說明對於兩個位元組組成的字元,%C 才是正確的選擇。

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