how to use stringByTrimmingCharactersInSet in NSString

Christien picture Christien · Jan 4, 2013 · Viewed 13k times · Source

I have a string which gives the Date (below)

NSString*str1=[objDict objectForKey:@"date"];

 NSLog(@" str values2%@",str1); --> 04-Jan-13

Now Problem is I need to Trim the"-13" from here .I know about NSDateFormatter to format date.but I can't do that here.I need to trim that

For that I am using:-

 NSCharacterSet *charc=[NSCharacterSet characterSetWithCharactersInString:@"-13"];

 [str1 stringByTrimmingCharactersInSet:charc];  

But this does not work.this does not trim...how to do that..help

Answer

Stavash picture Stavash · Jan 4, 2013

Not sure why not use an NSDateFormatter but here's a very specific way to approach this (very bad coding practice in my opinion):

NSString *theDate = str1;
NSArray *components = [theDate componentsSeparatedByString:@"-"];
NSString *trimmedDate = [NSString stringWithFormat:@"%@-%@",[components objectAtIndex:0],[components objectAtIndex:1]];