您的位置:首页 > 移动开发 > IOS开发

ios字母与数字相互转化,ascll码转化

2016-08-24 16:06 495 查看
发个广告:ios开发两年了,一步步走来  关注公众号一起进步


NSString *string = @"A";

NSInteger int = [string characterAtIndex:0]; 
上面的结果胃65
 

 int 
 aaa= 65;
NSString *string = [NSString stringWithFormat:@"%c",aaa]; //
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,?,ト
 
显示结果表明,这个方法是正确的。对于两个字节组成的字符,是能显示出的。不知道其他语言会怎么样,没有条件去测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios string ascll