如何在 NSString 前面添加前导空格? [英] How can I add leading whitespace in front of the NSString?

查看:50
本文介绍了如何在 NSString 前面添加前导空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要字符串的长度总是 5...例如,如果

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

我通过hello",我得到"hello"
我通过"xml",我得到"xml"(xml"前两个空格);
我通过 "i",我得到 " i"(i"前四个空格).

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.

推荐答案

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];

    }

//现在你可以使用 yourString 了.它被格式化了.

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

这篇关于如何在 NSString 前面添加前导空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆