日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

中文字符ASCII码和NSString相互转换

發布時間:2024/9/30 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 中文字符ASCII码和NSString相互转换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在xcode中,文件以utf8格式保存。因此,其中變量對象也是以utf8格式保存。不同語言的utf8編碼不一樣,英文的utf8編碼和ascii碼一樣。 不同語言的每個字符的utf8編碼的字節數不一樣,字節碼也不一樣。對于英文字符,查看它的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碼轉成字符有兩種format,分別為%c和%C。 /* %c 8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit. %C 16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit. */ 使用[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 = @"カントリー"; theChar = [theString characterAtIndex:2]; theString1 = [NSString stringWithFormat:@"%c", theChar]; theString2 = [NSString stringWithFormat:@"%C", theChar]; NSLog(@"theString=%@,%d,%@,%@",theString,theChar,theString1,theString2); 2013-09-12 15:36:27.849 XYShopping[1892:18e03] theString=g,103,g,g 2013-09-12 15:36:27.849 XYShopping[1892:18e03] theString=家,23478,?,家 2013-09-12 15:36:27.849 XYShopping[1892:18e03] theString=カントリー,12488,?,ト 顯示結果表明,這個方法是正確的。對于兩個字節組成的字符,是能顯示出的。不知道其他語言會怎么樣,沒有條件去測試。

總結

以上是生活随笔為你收集整理的中文字符ASCII码和NSString相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。