gpt4 book ai didi

objective-c - Objective C 字符串操作、查看、添加

转载 作者:行者123 更新时间:2023-12-03 18:04:44 26 4
gpt4 key购买 nike

我正在尝试操纵给我的一系列开放时间。

它的格式很差,我需要将其提高到与来自不同来源的另一条数据相同的标准。

周一至周三 930-1700 周四 900-1700 周五 930-1700
周一至周三 930-1700 周四 900-1700 周五 930-1700
周一至周四 930-1600 周五 930-1700
周一至周三 930-1700 周四 900-1700 周五 930-1700 周六 900-1200

如您所见,日期等的连字符之间并不总是有空格。

我需要用分号分隔它,如下所示:

周一至周三 930-1700;周四 900-1700;周五 930-1700
周一至周三 930-1700;周四 900-1700;周五 930-1700
周一至周四 930-1600;周五 930-1700
周一至周三 930-1700;周四 900-1700;周五 930-1700;周六 900-1200

不确定这是否是最好/最简单的解决方案,但我有想法检查零后面是否有空格,以及零后面是否是字母,例如 M、T、W、F 或 S。然后我会知道这是一组小时的结束,并用分号替换空格。我是 Objective C 的新手,真的不知道如何查看或检查 NSString 中的单个字符。这看起来也可能是一个复杂的解决方案。

同样相关的是,我需要将这些时间从 24 小时制转换为 12 小时制。例如,1700 至下午 5:00、0930 至上午 9:30。我知道我可以减去 1200 并添加 pm,但是如何在小时和分钟之间添加 : 并在上午 10:00 之前删除前导零?

抱歉文字太多,但我觉得最好在一开始就多解释一下。

干杯

最佳答案

// side note: you should probably not mess around with individual characters unless you're only dealing with ASCII

NSString *text = // all your text

NSMutableString *mutableText = [[text mutableCopy] autorelease]; // make a mutable copy so we can change in place

[mutableText replaceOccurrencesOfString:@"\t" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutableText length])]; // delete Tabs
[mutableText replaceOccurrencesOfString:@" -" withString:@"-" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutableText length])]; // make all dashes consistent
[mutableText replaceOccurrencesOfString:@"- " withString:@"-" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutableText length])];

NSArray *words = [mutableText componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; // split each line

NSMutableString *cleanedText = [NSMutableString stringWithCapacity:0]; // will hold cleaned-up string

// go thru each line and insert semi-colon after all but the last hours
for (NSString *record in words)
{
// assumes all hours end in zero
NSString *newRecord = [record stringByReplacingOccurrencesOfString:@"0 " withString:@"0;" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [record length])];
[cleanedText appendFormat:@"%@\n", newRecord];
}

NSLog(@"%@", cleanedText); // all done

不要犹豫提出后续问题,但如果您对相关主题还有其他具体问题,请继续在 StackOverflow 上将其设为新问题。它使其更易于搜索,这是该网站的主要目标。

关于objective-c - Objective C 字符串操作、查看、添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3209337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com