如何用空格填充 NSString?

发布于 2024-12-23 05:50:22 字数 205 浏览 7 评论 0原文

例如,我需要 NSString 至少有 8 个字符......而不是使用循环在其上添加左侧填充空格,有没有办法做到这一点?

Examples:

Input:    |Output:
Hello     |   Hello
Bye       |     Bye
Very Long |Very Long
abc       |     abc

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

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

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

发布评论

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

评论(3

迷路的信 2024-12-30 05:50:22

以下是如何执行此操作的示例:

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

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;
}
等风来 2024-12-30 05:50:22

我只是做了这样的事情:

    NSLog(@"%*c%@", 14 - theString.length, ' ', theString);

此外,14是你想要的宽度。

I just do something like this:

    NSLog(@"%*c%@", 14 - theString.length, ' ', theString);

Moreover, 14is the width that you want.

红尘作伴 2024-12-30 05:50:22

您可以通过 -[NSMutableStringappendFormat:] 和所有其他 NSString“格式”方法使用 C 语言 printf 格式化。它不尊重 NSString(对 %@ 进行格式化),因此您需要将它们转换为 ASCII。

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
*/

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