objective-c right padding

独自空忆成欢 提交于 2019-12-02 08:26:21

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.

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

NSString* padr(NSString* string, NSUInteger length, NSString *repl)
{
    return [string stringByPaddingToLength:length withString:repl startingAtIndex: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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!