How do you join an NSArray of [Number numberWithChar: c]'s into an NSString?

▼魔方 西西 提交于 2019-12-21 22:18:02

问题


When I use componentsJoinedByString, I just get a long string of digits.

Edit: I realize this task is confusing. Why on earth would anyone populate an NSArray with NSNumbers if they wanted an NSString? The answer is that I'm writing an extensible unit test framework. The basic functions genNum, genBool, and genChar generate NSNumbers with random int, BOOL, and char values respectively. Then there's genArray which generates a random array using a specified generator. So to construct a random NSString, one would run genArray using the genChar generator, and transform the resulting NSArray into an NSString.

The characters are only stored as NSNumbers instead of chars due to a technicality: genArray accepts a block and calls the block 100-odd times to populate the NSArray. Blocks must hold ObjC objects; not primitive types.

So the question remains: How do you join an NSArray of [NSNumber numberWithChar: c]'s into an NSString?


回答1:


componentsJoinedByString joins the array elements into a string with the separator character between them. The array elements are converted to strings (if not already NSString" using the description method. If you have n array of NSNumbers I would expect an interesting result.




回答2:


Why not fill your array with [NSString stringWithCharacters:c length:1]? Then componentsJoinedByString: ought to work. (Check the docs on stringWithCharacters:length:; the above is just for illustration. You might have to use &c, for example.)




回答3:


+ (NSString *) genString {
    NSArray* arr = [self genArray: ^() { return [ObjCheck genChar]; }];

    NSMutableString* s = [NSMutableString stringWithCapacity: [arr count]];

    int i;
    for (i = 0; i < [arr count]; i++) {
        [s appendString: [NSString stringWithFormat: @"%c", [[arr objectAtIndex: i] charValue]]];
    }

    return s;
}



回答4:


+ (id)genString {
    NSArray *chars = [self genArray:^{ return [ObjCheck genChar]; }];

    if ([chars count] == 0) {
        return @"";
    }

    unichar *buffer = malloc(sizeof(unichar) * [chars count]);

    [chars enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
        buffer[idx] = (unichar)[num charValue];
    }];

    return [[[NSString alloc] initWithCharactersNoCopy:buffer length:[chars count] freeWhenDone:YES] autorelease];
}

This particular solution will assume chars >127 should be treated as unicode codepoints (which basically means, for char-sized values, as ISO-8859-1). It also avoids copying the buffer when creating the resulting string.



来源:https://stackoverflow.com/questions/7748616/how-do-you-join-an-nsarray-of-number-numberwithchar-cs-into-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!