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

不问归期 提交于 2019-12-04 19:14:45

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.

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.)

+ (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;
}
+ (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.

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