0

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

Chirag Kothiya
  • 874
  • 4
  • 12
  • 24
Jester
  • 2,849
  • 5
  • 30
  • 43
  • possible duplicate of [String Padding in C](http://stackoverflow.com/questions/276827/string-padding-in-c?rq=1) – D. Ben Knoble Feb 02 '15 at 21:25
  • The way I see it printf does not produce a NSString but I might be wrong – Jester Feb 02 '15 at 21:31
  • A document application such as Dash makes it much easier to find API methods. Just by entering "padd" I see the method. – zaph Feb 02 '15 at 21:52

3 Answers3

3

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.

mc01
  • 3,652
  • 18
  • 24
0

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

NSString* padr(NSString* string, NSUInteger length, NSString *repl)
{
    return [string stringByPaddingToLength:length withString:repl startingAtIndex:0];
}
Michael Dorner
  • 14,449
  • 11
  • 73
  • 105
0
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;
}
Chase
  • 1,856
  • 11
  • 12