Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad NSString with spaces?

For example, I need the NSString have at least 8 chars....instead of using a loop to add the left pad spaces on this, is there anyway to do it?

Examples:

Input:    |Output:
Hello     |   Hello
Bye       |     Bye
Very Long |Very Long
abc       |     abc
like image 613
DNB5brims Avatar asked Dec 28 '11 02:12

DNB5brims


2 Answers

Here is an example of how you can do it:

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;
}
like image 188
Sergey Kalinichenko Avatar answered Sep 19 '22 18:09

Sergey Kalinichenko


I just do something like this:

    NSLog(@"%*c%@", 14 - theString.length, ' ', theString);

Moreover, 14is the width that you want.

like image 28
PlusA Avatar answered Sep 21 '22 18:09

PlusA