问题
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
回答1:
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;
}
回答2:
I just do something like this:
NSLog(@"%*c%@", 14 - theString.length, ' ', theString);
Moreover, 14is the width that you want.
回答3:
You can use C language printf formatting with -[NSMutableString appendFormat:] and all other NSString "format" methods. It doesn't respect NSString (do formatting on %@), so you need to convert them to ASCII.
String Padding in C
- (NSString *)sample {
NSArray<NSString *> *input = @[@"Hello", @"Bye", @"Very Long", @"abc"];
NSMutableString *output = [[NSMutableString alloc] init];
for (NSString *string in input) {
[output appendFormat:@"%8s\n", string.UTF8String];
}
return output;
}
/*
Return value:
Hello
Bye
Very Long
abc
*/
回答4:
if you need the same answer in a method, I had to create one for use in my projects. original code by dashblinkenlight
- (NSString *) LeftPadString: (NSString*) originalString LengthAfterPadding: (int)len paddingCharacter: (char) pad
{
int add = (int) (len - originalString.length);
NSString* paddingCharString = [NSString stringWithFormat:@"%c" , pad];
if (add > 0)
{
NSString *pad = [[NSString string] stringByPaddingToLength:add withString: paddingCharString startingAtIndex:0];
return [pad stringByAppendingString:originalString];
}
else
return originalString;
}
来源:https://stackoverflow.com/questions/8651210/how-to-pad-nsstring-with-spaces