Jester
Jester

Reputation: 3317

objective-c right padding

hello all hope someone can help with that. I was browsing the net and nothing really seems to make sense :S

so I have a string lets say: "123" and I would like to use a function like:

padr("123", 5, 'x')

and the result should be:

"123xx"

Sorry but Objective-C is a nightmare when dealing with strings :S

Upvotes: 0

Views: 732

Answers (3)

Chase
Chase

Reputation: 2304

NSMutableString* padString(NSString *str, int padAmt, char padVal)
{
    NSMutableString *lol = [NSMutableString stringWithString:str];

    while (lol.length < padAmt) {
        [lol appendFormat:@"%c", padVal];
     }

    return lol;

}

And the Call

int main(int argc, const char * argv[]) {
    @autoreleasepool {


        NSLog(@"%@", padString(@"123", 5, 'x'));


    }
    return 0;
}

Upvotes: 0

Michael Dorner
Michael Dorner

Reputation: 20135

What about the NSString method stringByPaddingToLength:withString:startingAtIndex:.

NSString* padr(NSString* string, NSUInteger length, NSString *repl)
{
    return [string stringByPaddingToLength:length withString:repl startingAtIndex:0];
}

Upvotes: 0

mc01
mc01

Reputation: 3770

You could create your own method to take the initial string, desired length, and padding character (as I was starting to do & also described in a few similar questions)

Or you could use the NSString method Apple already provides ;)

NSString *paddedString = [@"123" 
                           stringByPaddingToLength: 5 
                           withString: @"x" startingAtIndex:0];

See NSString Class Reference for this method.

Upvotes: 3

Related Questions