您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

中文字元、ASCII 碼與 NSString 的相互轉換

編輯:iOS 開發綜合

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

不同語言的每個字元,其 UTF-8 編碼的位元組數與位元組碼都不一樣。對於英文字元,查看它的 ASCII 碼很簡單——把字元取出來就是它的 ASCII 碼。其實對於非英文字元,取字符集編碼的方式也是如此,很多文檔都統稱為「取 ASCII 碼」。

網上有很多例子介紹如何讓字元與 ASCII 碼相互轉換,但它們都沒提及如何轉換中文等非英文字元,直接用這些方法都會得到亂碼。

英文轉換測試

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

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

用中文測試時,[NSString stringWithFormat:@"%c", asciiCode] 得到的是亂碼,也就是根本沒識別正確。

問題根源與解法

先了解 stringWithFormat 中的兩種 format:把 ASCII 碼轉成字元有 %c 和 %C 兩種。

/*
%c  8-bit unsigned character (unsigned char), 以 ASCII 字元列印,
    若非 ASCII 字元則以八進位 \ddd 或 Unicode 十六進位 \udddd 表示。
%C  16-bit Unicode character (unichar),規則同上。
*/

關鍵就在這裡:使用 [NSString stringWithFormat:@"%C", asciiCode](大寫的 %C),就能正確得到所要的字元。

驗證

分別以英文、中文、日文舉例:

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 = @"カントリー";
theChar = [theString characterAtIndex:2];
theString1 = [NSString stringWithFormat:@"%c", theChar];
theString2 = [NSString stringWithFormat:@"%C", theChar];
NSLog(@"theString=%@,%d,%@,%@",theString,theChar,theString1,theString2);

輸出結果表明:

theString=g,103,g,g
theString=家,23478,?,家
theString=カントリー,12488,?,ト

可以看到,用 %c 時中文會顯示成問號(亂碼),而用 %C 則能正確顯示。對於兩個位元組組成的字元,這個方法完全可行。

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