Array created from separator?

Discussion in 'Mac Programming' started by Buschmaster, Sep 3, 2008.

  1. macrumors 65816

    Buschmaster

    Joined:
    Feb 12, 2006
    Location:
    Minnesota
    #1
    Anyone know of an easy way to create an array from a designated separator in obj-c?

    What I mean is I want to create an array like
    Code:
    {hello,world,how,are,you}
    out of something like:
    Code:
    @"hello:world:how:are:you"
    There is a way around this for me but if someone knows of a way to do this I can really cut out quite a few middle men.
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Code:
    - (NSArray *)componentsSeparatedByString:(NSString *)separator
    Something like:

    Code:
    #import <Foundation/Foundation.h>
    
    int main(int argc, char *argv[]) {
      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
      NSString *myString = @"Hello:World,:how:are:you?";
      NSArray *myComponents = [myString componentsSeparatedByString:@":"];
      int compLength = [myComponents count];
      unsigned int x = 0;
      for(x = 0; x < compLength; x++) {
        NSLog(@"Component %u is: %@",x+1,[myComponents objectAtIndex:x]);
      }
      [pool release];
      return 0;
    }
    I am assuming you wanted an NSArray of NSStrings, but you didn't say for sure. You can get a real id array from this, but I wouldn't recommend it.

    -Lee

    Eh, just in case:
    Code:
    #import <Foundation/Foundation.h>
    
    int main(int argc, char *argv[]) {
      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
      NSString *myString = @"Hello:World,:how:are:you?";
      NSArray *myComponents = [myString componentsSeparatedByString:@":"];
      int compLength = [myComponents count];
      id *myTerribleCStyleArray = malloc(compLength * sizeof(id));
      [myComponents getObjects:myTerribleCStyleArray];
      
      unsigned int x = 0;
      for(x = 0; x < compLength; x++) {
        NSString *oneString = myTerribleCStyleArray[x];
        NSLog(@"Component %u is: %@",x+1,oneString);
      }
      
      [pool release];
      return 0;
    }
    
    This will be equivalent to:
    Code:
      NSString *mySecondTerribleArray[] = {@"Hello",@"World,",@"how",@"are",@"you?"};
      for(x = 0; x < 5;  x++){
        NSString *oneString = mySecondTerribleArray[x];
        NSLog(@"Component %u is: %@",x+1,oneString);
      }
    
    This most resembles what you posted, but again, I hope it's not what you really want.

    -Lee
     
  3. thread starter macrumors 65816

    Buschmaster

    Joined:
    Feb 12, 2006
    Location:
    Minnesota
    #3
    Ah, componenetsSeparatedByString is just what I was looking for! Thanks!
     
  4. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX

Share This Page