如何在 NSString 前面添加前导空格?

发布于 2024-10-20 05:31:19 字数 237 浏览 4 评论 0原文

我需要字符串的长度始终为 5... 例如,如果

我传递 hello",我会得到 "hello"
我通过 "xml",我得到 " xml" (“xml”之前有两个空格);
我通过 "i",得到 " i" (“i”之前有四个空格)。

最有效的方法是什么?谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原谅过去的我 2024-10-27 05:31:19

我想这可能会有所帮助:

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

I suppose this might help:

int maxLength = 5;
NSString *text = @"xml";
NSString *result = [text stringByPaddingToLength:(maxLength-[text length]) withString:@" " startingAtIndex:0];
傻比既视感 2024-10-27 05:31:19
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了。它已经格式化了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文