Wednesday, July 21, 2010

Easy NSString substring

Sadly, creating a simple substring in Objective-C isn't quite as obvious as in other languages. Here's a basic method to grab a substring of a given string before a defined character, in my case the ":" character:

NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(0, end.location)]];

If you wanted grab a string between two characters, you could do:

NSRange start = [_contentsOfElement rangeOfString:@"|"];
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(start.location, end.location)]];

3 comments:

  1. Thanks! But I'm not sure the end.location is handled correctly... because the substringWithRange shoud expect the starting position and the length.

    ReplyDelete
  2. Yeh should be using int _length = end.location - start.location; and then using that as the 2nd param in substringWithRange.

    ReplyDelete