开发者

Help with NSString of int's to NSString of ASCII characters?

开发者 https://www.devze.com 2023-03-16 00:27 出处:网络
I have implemented some code to convert a NSString of \"text\" to an NSString of (ASCII) ints, like so:

I have implemented some code to convert a NSString of "text" to an NSString of (ASCII) ints, like so:

@"Hello" is converted to @"72 101 108 108 111"

However, I am having quite a bit of difficulty doing the opposite. Starting with a string of ints (with the spaces) and converting back to the plain string of text.

What I need: @"72 101 108 108 111" must be converted to @"Hello"

I have tried bre开发者_运维技巧aking up the input string into an int array, iterating through it, and using repeatedly the following:

[NSString stringWithFormat:@"%c", decCharArray[i]]

However, the problem with that is that it parses each particular digit into ASCII, converting the 7, the 2, the space, the 1, etc.

Thanks a ton in advance.


Sounds like you have the right approach. Try using [string componentsSeparatedByString:@" "] to split the string at the spaces. Then you can convert each of those to numbers, and back into strings.


There is no real magic on it. Since you'll be using ASCII, to convert an int to a char all you have to do is an assignment, as you may already know:

char a = 65; /* a contains 'A' */

NSString has a very convenient method componentsSeparatedByString: that will return an array of strings containing your numbers, and you can get an int from a string with the intValue method. Thus, all you have to do is to split the string and iterate through the components assigning their int value to a char array. Here is an example function that does that:

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];
}

And a simple use of it, with your "Hello" example:

NSString *string = @"72 101 108 108 111";
NSLog(@"%@", TextFromAsciiCodesString(string));

Actually, it's a bit different as your example was "Hell^K" :-)


You can also trying using NSString's enumerateSubstringsInRange:options:usingBlock:.

Usage

NSString * hello = @"72 101 108 108 111";

NSMutableString * result = [NSMutableString string];
[hello enumerateSubstringsInRange:NSMakeRange(0, [data length])
                          options:NSStringEnumerationByWords
                       usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                           [result appendString:[NSString stringWithFormat:@"%c", [substring intValue]]];
                       }];

NSLog(@"%@", result);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号