How do I remove leading & trailing whitespace of NSString inside an NSArray?

The NSArray and the contained NSString objects are all immutable. There’s no way to change the objects you have. Instead you have to create new strings and put them in a new array: NSMutableArray *trimmedStrings = [NSMutableArray array]; for (NSString *string in arrayRefineSubjectCode) { NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; [trimmedStrings addObject:trimmedString]; } arrayRefineSubjectCode = … Read more

Converting HEX NSString To NSData

NSString *command = @”72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553″; command = [command stringByReplacingOccurrencesOfString:@” ” withString:@””]; NSMutableData *commandToSend= [[NSMutableData alloc] init]; unsigned char whole_byte; char byte_chars[3] = {‘\0′,’\0′,’\0’}; int i; for (i=0; i < [command length]/2; i++) { byte_chars[0] = [command characterAtIndex:i*2]; byte_chars[1] = [command characterAtIndex:i*2+1]; whole_byte = strtol(byte_chars, NULL, 16); [commandToSend appendBytes:&whole_byte length:1]; } NSLog(@”%@”, commandToSend);

Break up long formatted NSString over multiple lines

Yes there is. Adjacent strings will be concatenated for you by the compiler. NSString *info = [NSString stringWithFormat:@”\n Elapsed Time \n” “Battery Level: \n” “Torque: \n” “Energy Used \n” “Energy Regenerated:\n Cadence: \n” “Battery Temp: \n” “Motor Temp: \n” “Incline: \n Speed MPH: \n” “Speed KPH:\n” “Avg Speed MPH: %f \n” “Avg Speed KPH:\n” “Distance … Read more

Cocoa – Trim all leading whitespace from NSString

This creates an NSString category to do what you need. With this, you can call NSString *newString = [mystring stringByTrimmingLeadingWhitespace]; to get a copy minus leading whitespace. (Code is untested, may require some minor debugging.) @interface NSString (trimLeadingWhitespace) -(NSString*)stringByTrimmingLeadingWhitespace; @end @implementation NSString (trimLeadingWhitespace) -(NSString*)stringByTrimmingLeadingWhitespace { NSInteger i = 0; while ((i < [self length]) && … Read more

Replace only the first instance of a substring in an NSString

Assuming the following inputs: NSString *myString = @”My blue car is bigger then my blue shoes or my blue bicycle”; NSString *original = @”blue”; NSString *replacement = @”green”; The algorithm is quite simple: NSRange rOriginal = [myString rangeOfString:original]; if (NSNotFound != rOriginal.location) { myString = [myString stringByReplacingCharactersInRange:rOriginal withString:replacement]; }