Reputation: 711
I have a date in string format like: 9th march 2013,15th october 2012,etc.
How can I convert this into like: 9th March 2013, 15th October 2013?
I done like: [str capitalizedString]
but it will also capitalize the T from th.
Upvotes: 1
Views: 237
Reputation: 14995
Assuming this is your string below. So on the basis of that it will only upper the month in the below date format:-
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);
OutPut:-
9th March 2013, 15th October 2013
Upvotes: 1
Reputation: 107121
You can do it like:
- (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;
}
You can call it like:
[self changeMonthToCapital:@"9th march 2013"];
Upvotes: 0
Reputation: 4671
If you string format same as above: then you can do it in such a way:
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);
You can store final string into NSString
by loop through to finalArray
. Or with in above loop itself.
Upvotes: 0