How can I add leading whitespace in front of the NSString?

时光毁灭记忆、已成空白 提交于 2019-12-11 07:01:03

问题


I need the String always have length 5... for example, if

I pass hello", I get "hello"
I pass "xml", I get " xml" (two spaces before "xml");
I pass "i", I get " i" (four spaces before "i").

What is the most efficient way to do it? Thank you.


回答1:


NSMutableString *yourString;//your string
NSMutableString *string;
if([string length]<5){
   NSInteger length = 5-[string length];
     for(int i=0;i<length;i++){
        [string appendFormat:@" "];
       }
[yourString appendString:string];

    }

//now you can use yourString .it is formatted.




回答2:


I suppose this might help:

int maxLength = 5;
NSString *text = @"xml";
NSString *result = [text stringByPaddingToLength:(maxLength-[text length]) withString:@" " startingAtIndex:0];


来源:https://stackoverflow.com/questions/5178332/how-can-i-add-leading-whitespace-in-front-of-the-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!