how to use stringByTrimmingCharactersInSet in NSString

13,140

Solution 1

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

Solution 2

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]];

Solution 3

Something like this:

NSString *trimmed = [textStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

or this:

NSString *trimmed = [textStr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-13"];

Solution 4

what you have done is correct. Only thing is stringByTrimmingCharactersInSet returns NSString. So you need to assign this value to NSString, like

str1 = [str1 stringByTrimmingCharactersInSet:charc];

Solution 5

if you're sure you have your string always formatted like "NN-CCC-NN" you can just trim the first 6 chars:

NSString* stringToTrim = @"04-Jan-13";
NSString* trimmedString =  [stringToTrim substringToIndex:6];
NSLog(@"trimmedString: %@", trimmedString); // -> trimmedString: 04-Jan
Share:
13,140
Christien
Author by

Christien

Updated on June 25, 2022

Comments

  • Christien
    Christien almost 2 years

    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