objective-c - 如何用空格填充 NSString?

标签 objective-c nsstring padding

例如,我需要 NSString 至少有 8 个字符....而不是使用循环在其上添加左填充空格,有没有办法做到这一点?

Examples:

Input:    |Output:
Hello     |   Hello
Bye       |     Bye
Very Long |Very Long
abc       |     abc

最佳答案

这是一个如何做到这一点的例子:

int main (int argc, const char * argv[]) {
    NSString *str = @"Hello";
    int add = 8-[str length];
    if (add > 0) {
        NSString *pad = [[NSString string] stringByPaddingToLength:add withString:@" " startingAtIndex:0];
        str = [pad stringByAppendingString:str];
    }
    NSLog(@"'%@'", str);
    return 0;
}

关于objective-c - 如何用空格填充 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8651210/

相关文章:

objective-c - 在 NSClassFromString() 返回的类上调用类方法

ios - UITextView 中希伯来字符的奇怪格式

css - 当位置是相对的时,元素的填充和边距会改变吗?

html - 带有填充的 div 内的 img

c# - MonoTouch 中 CGImageCreateWithImageInRect 的等价物是什么?

ios - NSPredicate 在 NSArray 上搜索任何对象

ios - 仅使用一个托管对象预填充核心数据

ios - 将 NS_OPTIONS 枚举 (UIRemoteNotificationType) 位掩码转换为 NSString 分隔值

ios - 将 NSData 转换为 NSString 返回随机字符

jquery - 填充、边距和背景颜色不会消失