Basic string manipulation

Discussion in 'iOS Programming' started by nashyo, Jan 13, 2013.

  1. nashyo macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol
    #1
    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"
     
  2. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #2
    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
     
  3. nashyo thread starter macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol

Share This Page