NSString填充/字符之间的空格

时间:2012-06-16 03:37:08

标签: objective-c ios nsstring padding kerning

我正在Obj.C中寻找一种简单的方法来在我的字符串的每个字符之间添加一个空格。所以“1234”看起来就像“1 2 3 4”。

我在这里找到了一个完美的javascript示例:https://stackoverflow.com/a/7437422/949538

有没有人知道Obj.C类似的东西? Kerning是iOS中的PITA,这最终只是我需要的......

思考/评论?

谢谢! - 德鲁

3 个答案:

答案 0 :(得分:9)

为了正确地做到这一点,考虑到DavidRönnqvist评论中提到的问题,请做这样的事情:

NSMutableString* result = [origString mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
                           options:NSStringEnumerationByComposedCharacterSequences | NSStringEnumerationSubstringNotRequired
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
     if (substringRange.location > 0)
         [result insertString:@" " atIndex:substringRange.location];
}];

答案 1 :(得分:5)

试试这个:

NSString *string =[NSString stringWithString:@"1234"];
NSMutableArray *buffer = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
    [buffer addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}
NSString *final_string = [buffer componentsJoinedByString:@" "];

答案 2 :(得分:0)

这样做:

    NSString *string =[NSString stringWithString:@"1234"];

    NSMutableString *spacedString= [NSMutableString stringWithString:[NSString stringWithFormat:@"%C",[string characterAtIndex:0]]];

    for(int i = 1; i<[string length];i++)
    {
        [spacedString appendString:[NSString stringWithFormat:@" %C",[string characterAtIndex:i]]];
    }