在NSString中是否有setwidth?

时间:2012-01-20 05:38:46

标签: iphone objective-c ios ipad nsstring

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

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类型函数?

2 个答案:

答案 0 :(得分:3)

你是这样做的吗?

/ *定义辅助方法* /

- (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

答案 1 :(得分:0)

您必须使用NSMutableString来实现此目的。逻辑是:

  1. 检查最大长度字符串,例如maxLength
  2. 现在运行for循环来迭代所有字符串,如果字符串的当前长度小于maxLength,则用“”(空格)附加字符串。
  3. 现在有了最终结果,你将获得所有相同长度的字符串。