在iphone中大写字符串

时间:2013-12-23 11:24:46

标签: ios iphone objective-c string nsstring

我有一个字符串格式的日期,如:2013年3月9日,2012年10月15日,等等。

如何将其转换为:2013年3月9日,2013年10月15日?

我完成了:[str capitalizedString]但它也会将 T 大写。

3 个答案:

答案 0 :(得分:1)

假设这是你的字符串。所以在此基础上它只会在以下日期格式的月份上升: -

 NSString *str= @"9th march 2013, 15th October 2013";
NSString *str1=[str stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:[[str substringWithRange:NSMakeRange(0, 5)]uppercaseString]];
NSString *str2=[str1 stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:[[str substringWithRange:NSMakeRange(0, 3)]lowercaseString]];
NSLog(@"%@",str2);

输出: -

9th March 2013, 15th October 2013

答案 1 :(得分:0)

如果你的字符串格式与上面相同:那么你可以这样做:

NSString *yourString = @"9th march 2013,15th october 2012";
NSArray *array = [yourString componentsSeparatedByString:@","];

NSMutableArray *finalArray = [[NSMutableArray alloc]init];

for (int i =0 ; i < [array count]; i++) {

    NSString *innerStr = [array objectAtIndex:i];

    NSArray *newArray = [innerStr componentsSeparatedByString:@" "];

    NSString *monthStr = [newArray objectAtIndex:1];

    monthStr = [[[monthStr substringToIndex:1]uppercaseString]stringByAppendingString:[monthStr substringFromIndex:1]];

    NSString *finalString = [NSString stringWithFormat:@"%@ %@ %@", [newArray objectAtIndex:0],monthStr,[newArray objectAtIndex:2]];

    [finalArray addObject:finalString];
}

NSLog(@"%@",finalArray);

您可以通过循环到NSString将最终字符串存储到finalArray。或者在上面循环中。

答案 2 :(得分:0)

你可以这样做:

- (NSString *)changeMonthToCapital:(NSString *)str
{
    // You need to do proper exception handling
    NSMutableArray *components = [[str componentSeparatedBy:@" "] mutableCopy];
    NSString *newTxt           = [components objectAtIndex:1];
    NSString *changedTxt       = [newTxt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[newTxt substringToIndex:1] uppercaseString]];
    [components  replaceObjectAtIndex:1 withObject:changedTxt];
    str = [components  componentsJoinedByString:@" "];
    return str;
}

你可以这样称呼:

[self changeMonthToCapital:@"9th march 2013"];