Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

nashyo

macrumors 6502
Original poster
Oct 1, 2010
299
0
Bristol
In Javascript you can simply state that you want the first three characters of a string like so:

Code:
console.log(@"IAmRobertNash".substring(0,3));

However, in Objective-C I can't find such an easy way to do this. I can accomplish the same with the following:

Code:
NSString *string = @"IAmRobertNash";
NSRange range = [string rangeOfString:@"Ro"];
NSLog(@"%@", [string substringToIndex:range.location]);

But does anyone know of an approach in objective-c or c that is as simple or equivalent as the javascript example above?

Further; how would get the first three characters from the following string in Objective-C, easily?

Code:
@"IAmRobertNashRobertNash"
 
Code:
NSString *string = @"IAmRobertNashRobertNash";
NSString *first3 = [string substringToIndex:3];

Alternatively, if you wanted to get a substring containing everything from 3 to 9 (the first Robert), for example, you could use this:

Code:
NSString *from3To9 = [string substringWithRange:NSMakeRange(3, 6)];

Note that the second argument to NSMakeRange() is the length of the range, not the ending index of the range.

If you find that a bit too long and wish that string had a name with a shorter method that simply took two integers rather than the NSRange struct, you could consider using a category to give NSString some new methods:

http://macdevelopertips.com/objective-c/objective-c-categories.html
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.