当前位置: 代码迷 >> Iphone >> 怎么把这一段字符串转换成123456
  详细解决方案

怎么把这一段字符串转换成123456

热度:7   发布时间:2016-04-25 06:24:03.0
怎样把这一段字符串转换成123456
NSString *str=@"313233343536";//这是123456的ascii码
怎样把这一段字符串转换成123456呢
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; //

------解决方案--------------------
- (NSString *)TextFromAsciiCodesString:(NSString *)string
{
NSArray *components = [string componentsSeparatedByString:@" "];
NSUInteger len = [components count];
char new_str[len+1];

int i;
for (i = 0; i < len; ++i)
new_str[i] = [[components objectAtIndex:i] intValue];

new_str[i] = '\0';

return [NSString stringWithCString:new_str
encoding:NSASCIIStringEncoding];
}
转换后输出就是123456
------解决方案--------------------
C/C++ code
NSString *str=@"495051525354";    const char* cstr = [str UTF8String];    printf("%s\n", cstr);        char result[strlen(cstr) / 2 + 1];    int resultIdx = 0;    for(int i=0; i<strlen(cstr); i+=2){        char* tmp = malloc(3);        tmp[0] = cstr[i];        tmp[1] = cstr[i+1];        tmp[2] = '\0';        int a = atoi(tmp);        //printf("%d\n", a);        result[resultIdx++] = a;        free(tmp);    }    result[strlen(cstr) / 2] = '\0';    printf("%s\n", result);
------解决方案--------------------
C/C++ code
NSString *str=@"495051525354";    const char* cstr = [str UTF8String];    printf("%s\n", cstr);        char result[strlen(cstr) / 2 + 1];    int resultIdx = 0;    for(int i=0; i<strlen(cstr); i+=2){        char* tmp = malloc(3);        tmp[0] = cstr[i];        tmp[1] = cstr[i+1];        tmp[2] = '\0';        int a = atoi(tmp);        //printf("%d\n", a);        result[resultIdx++] = a;        free(tmp);    }    result[strlen(cstr) / 2] = '\0';    printf("%s\n", result);
------解决方案--------------------
楼主的ASCII码没错,是16进制的