Search code examples
iphoneiosnsstringnscharacterset

how to use stringByTrimmingCharactersInSet in NSString


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


Solution

  • But this does not work.this does not trim...

    It does trim, but since NSString is immutable, the trimmed string is thrown away, because you do not assign it to anything.

    This would work (but do not do it like that!)

    str1 = [str1 stringByTrimmingCharactersInSet:charc];
    

    What you do is not trimming, it's taking a substring. NSString provides a much better method for that:

    str1 = [str1 substringToIndex:6]; // Take the initial 6 characters