我想用固定宽度的空格附加我的字符​​串;例如,我想以这种格式显示数据:

1   faizan   1    locked    10/20/2008
1   faizan   1    locked    10/20/2008
1   faizan   1    locked    10/20/2008
1   faizan   1    locked    10/20/2008

但这仅适用于相同长度的字符串。如果字符串像这样不同:
1   faizan   1    locked    10/20/2008
2   faizanali   1    locked    10/20/2008
3   ali turab gilani    1    locked    10/20/2008

那么这并不能修复空格。为了我可以用相同数量的空格显示数据,我尝试了这个:
NSString *titleColumn = [[NSString stringWithFormat:@"%@:", title] stringByPaddingToLength:20 withString:@" " startingAtIndex:0];
serializedValue = [serializedValue stringByAppendingFormat:@"%@%@", titleColumn, value];

但这也不起作用。 Objective-C 是否像 C++ 和其他语言一样具有 setwidth 类型的函数?

最佳答案

你是这样做的吗?

/* 定义一个辅助方法 */

- (NSString *)formattedStringWithStrings:(NSArray *)strings {

    NSString *str1 = [[strings objectAtIndex:0] stringByPaddingToLength:3 withString:@" " startingAtIndex:0];
    NSString *str2 = [[strings objectAtIndex:1] stringByPaddingToLength:20 withString:@" " startingAtIndex:0];
    NSString *str3 = [[strings objectAtIndex:2] stringByPaddingToLength:3 withString:@" " startingAtIndex:0];
    NSString *str4 = [[strings objectAtIndex:3] stringByPaddingToLength:10 withString:@" " startingAtIndex:0];
    NSString *str5 = [[strings objectAtIndex:4] stringByPaddingToLength:15 withString:@" " startingAtIndex:0];
    return [NSString stringWithFormat:@"%@%@%@%@%@", str1, str2, str3, str4, str5];
}

/* 使用辅助方法 */
NSArray *strings = [NSArray arrayWithObjects:@"1", @"faizan", @"1", @"locked", @"10/20/2008", nil];
NSLog(@"%@", [self formattedStringWithStrings:strings]);

strings = [NSArray arrayWithObjects:@"2", @"faizanali", @"1", @"locked", @"10/20/2008", nil];
NSLog(@"%@", [self formattedStringWithStrings:strings]);

strings = [NSArray arrayWithObjects:@"3", @"ali turab gilani", @"1", @"locked", @"10/20/2008", nil];
NSLog(@"%@", [self formattedStringWithStrings:strings]);

/* 和输出 */
1  faizan              1  locked    10/20/2008
2  faizanali           1  locked    10/20/2008
3  ali turab gilani    1  locked    10/20/2008

关于iphone - NSString 中有 setwidth 吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8937192/

10-13 07:06