如何左填充 NSString 以使其适合固定宽度?

发布于 2024-11-17 20:27:21 字数 156 浏览 2 评论 0原文

我有 NSString 字符串,以 HH:MM:SS 表示时间,但 HH 和 MM 的数字可能会被省略。

我需要像这样对齐这些值的列:

1:01:43
  43:23
   7:00

执行此操作的最简单方法是什么?

I have NSString strings that represent times in HH:MM:SS but the HH and a digit of the MM may be omitted.

I need to align columns of these values like this:

1:01:43
  43:23
   7:00

What's the easiest way to do this?

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

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

发布评论

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

评论(6

时光倒影 2024-11-24 20:27:21

使用 NSString 类。像这样:

NSString * dateStr = @"05:30";
NSString * formattedStr = [NSString stringWithFormat:@"%8s", [str UTF8String]];

%8s 中的 8 是您想要在格式化字符串中的精度数字(或在本例中为字符)的数量。短于指定精度的输入字符串将用空格填充,长于指定精度的字符串将被截断。您可以在此处阅读有关 printf 格式字符串的更多信息。

编辑
感谢@Peter 指出了这一点。标准 C 与 Objective C 中的格式说明符之间存在一些(细微)差异。请参阅有关格式字符串说明符的 Apple 文档 此处

Make use of the stringWithFormat method provided in the NSString class. Something like this:

NSString * dateStr = @"05:30";
NSString * formattedStr = [NSString stringWithFormat:@"%8s", [str UTF8String]];

The 8 in %8s is the number of precision digits (or in this case characters) that you want in your formatted string. Input strings shorter than the specified precision will get left padded with spaces, strings longer than it will get truncated. You can read more about format strings for printf here.

Edit
Thanks to @Peter for pointing this out. There are some (minor) differences between the format specifiers in standard C, vs Objective C. Refer to Apples documentation on format string specifiers here.

怎会甘心 2024-11-24 20:27:21

填充代码 不同的,但可能会有所帮助

NSString *st = [@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];

abc……

[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];

ab

[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];

abc 。 。 。

请注意,填充中的第一个字符是空格

padding code Different one but might be helpful

NSString *st = [@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];

abc……

[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];

ab

[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];

abc . . .

notice that the first character in the padding is a space

乱了心跳 2024-11-24 20:27:21

我认为没有简单的方法。您可以在 NSString 上编写一个类别方法来执行此操作。

- (NSString *)stringByPaddingLeftToLength:(NSUInteger)aLength withString:(NSString *)padString {
    NSInteger lengthToPad = aLength - [self length];

    if ( lengthToPad > 0 ) {
        NSString * padding = [@"" stringByPaddingToLength:lengthToPad withString:padString startingAtIndex:0];
        NSString * paddedString = [padding stringByAppendingString:self];

        return paddedString;
    } else {
        return [[self copy] autorelease];
    }
}

I don't think there is an easy way. You can probably write a category method on NSString to do that.

- (NSString *)stringByPaddingLeftToLength:(NSUInteger)aLength withString:(NSString *)padString {
    NSInteger lengthToPad = aLength - [self length];

    if ( lengthToPad > 0 ) {
        NSString * padding = [@"" stringByPaddingToLength:lengthToPad withString:padString startingAtIndex:0];
        NSString * paddedString = [padding stringByAppendingString:self];

        return paddedString;
    } else {
        return [[self copy] autorelease];
    }
}
任谁 2024-11-24 20:27:21

如果您指的是固定的宽度,NSTextField (Cocoa) 和 UILabel (Cocoa Touch) 都可以让您设置对齐方式。对于 NSTextView 和自定义绘图,您需要创建一个 NSParagraphStyle(仅限 AppKit)或 CTParagraphStyle 并指定对齐方式。

If you mean a fixed point width, both NSTextField (Cocoa) and UILabel (Cocoa Touch) let you set the alignment. For NSTextView and custom drawing, you'll need to make an NSParagraphStyle (AppKit only) or CTParagraphStyle with the alignment specified.

一张白纸 2024-11-24 20:27:21

如果您希望它与比例字体(即不是等宽字体)显式对齐,那么您应该对字符串的每个组件使用不同的视图。

[hour]-[:]-[minute]-[:]-[second]
[hour]-[:]-[minute]-[:]-[second]
[hour]-[:]-[minute]-[:]-[second]

其中每一个 [things] 都是不同的 UILabel

If you want this to have explicit alignment with a proportional font (ie, not a monospace font), then you should use different views for each of the components of the string.

[hour]-[:]-[minute]-[:]-[second]
[hour]-[:]-[minute]-[:]-[second]
[hour]-[:]-[minute]-[:]-[second]

Where each one of those [things] is a different UILabel

晨敛清荷 2024-11-24 20:27:21

此解决方案对 iOS 有效:

在 iOS 中,您可以使用 UILabel 并将它们右对齐。当然,只有使用“固定字体”(例如 Courier New)才能实现完美对齐。
如果必须使用比例字体,唯一的方法是使用 NSString+UIKit 扩展在视图绘制上下文内的固定位置绘制字符串的所有字符:
所以理想情况下的流程是:
1.计算最长字符串的长度
2. 通过添加额外的空格来向左填充所有其他字符串
3.然后对于每个字符串迭代每个字符并将其绘制为特定位置(不要复制和粘贴此代码,只需使用它来获得一个想法;这是类似 obj-c 的伪代码)


CGFloat x=0; // the string start let's say at x=0
CGFloat dx=40; // distance between characters
for(NSInteger i=0;i<[myString length];i++) {
    NSString *char = [myString substringWithRange:NSRangeMake(i,1)];
    [char drawAtPoint:CGPointMake(x,y) withFont:myFont];
    x+=dx;
}

当然 dx 必须根据字体大小来选择。

This solution is valid for iOS:

in iOS you can use UILabel and right align them. Of course you will have a perfect alignment only if you use a "fixed font", like Courier New for example.
If you must use a proportional font, the only way is to use the NSString+UIKit extension to draw all characters of the string at fixed positions inside the view drawing context:
So ideally the flow is:
1. calculate the length of the longest string
2. left-pad all other strings by adding extra space
3. then for each string iterate on each character and draw it as a specific position (don't copy and paste this code, just use it to have an idea; this is obj-c-like pseudo-code)


CGFloat x=0; // the string start let's say at x=0
CGFloat dx=40; // distance between characters
for(NSInteger i=0;i<[myString length];i++) {
    NSString *char = [myString substringWithRange:NSRangeMake(i,1)];
    [char drawAtPoint:CGPointMake(x,y) withFont:myFont];
    x+=dx;
}

Of course dx must be chosen according to the font size.

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