如何用空格填充NSString? [英] How to pad NSString with spaces?
本文介绍了如何用空格填充NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我需要NSString至少有8个字符....而不是使用循环在其上添加左填充空格,反正有这样做吗?
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
推荐答案
以下是如何执行此操作的示例:
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;
}
这篇关于如何用空格填充NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文