Posts

Showing posts with the label nsstring

NSString's Split and Join crash course

Split a NSString is using the NSString instance method " componentsSeparatedByString " NSString * mystring = @"coding;is;kind;of;magic" ; NSArray * mysplitedstring = [mystring componentsSeparatedByString : @";" ]; The above code will produce an array containing the following element: coding is kind of magic To join an array of NSString back to a single NSString, use the NSArray instance method " componentsJoinedByString " NSString * mystring = [mysplitedstring componentsJoinedByString : @";" ]; That will give you back the NSString "coding;is;kind;of;magic"

Converting NSDate to NSString

Often we need to display a NSDate object on the screen with a specific format or by specific time zone. We can do this to the NSDate object easily. Quick note for doing this is: Create NSDateFormatter object (e.g. dateFormatter) Call dateFormatter setDateFormat Call dateFormatter stringFromDate Sample code NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:"yyyy-MM-dd 'at' HH:mm"]; NSString *dateDisplay = [dateFormatter stringFromDate:date]; NSLog(@"%@",dateDisplay); // 2012-02-08 at 18:30 To display AM / PM NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:"yyyy-MM-dd 'at' h:mm aaa"]; NSString *dateDisplay = [dateFormatter stringFromDate:date]; NSLog(@"%@",dateDisplay); // 2012-02-08 at 6:30 PM You can also set the NSDateFormatter to a difference timezone. (You might want to do this if your app's data has different timezone setti...

NSString's Substring Crash Course

NSString * s1 = @"abc1234"; NSLog(@"s1 = %@",s1); NSLog(@"substringFromIndex,4 : %@",[s1 substringFromIndex:4]); NSLog(@"substringToIndex,4 : %@",[s1 substringToIndex:4]); NSLog(@"substringWithRange,NSMakeRange,2,4 : %@",[s1 substringWithRange:NSMakeRange(2, 4)]); NSRange indexOfString = [s1 rangeOfString:@"bc"]; NSLog(@"substringFromIndex,indexOfString,bc : %@",[s1 substringFromIndex:indexOfString.location]); Will Produce the following output: s1 = abc1234 substringFromIndex,4 : 234 substringToIndex,4 : abc1 substringWithRange,NSMakeRange,2,4 : c123 substringFromIndex,indexOfString,bc : bc1234