cannyboy
cannyboy

Reputation: 24446

Getting the substring from a certain character in NSString

If I have an NSString that is initially:

"ABCDE*FGHI"

How do I make it turn into

"FGHI"

In other words, everything from the asterisk onwards is kept.

Likewise, how would I turn it into:

"ABCDE"

(everything up to the asterisk is kept)

Thanks

Upvotes: 33

Views: 27306

Answers (4)

Samuel De Backer
Samuel De Backer

Reputation: 3461

NSString *myString = @"ABCDE*FGHI"; 
NSArray *myArray = [myString componentsSeparatedByString:@"*"];
  • key 0 of myArray will contain @"ABCDE"
  • key 1 will contain @"FGHI"

If you want more than one character to be the separator,
use componentsSeparatedByCharactersInSet:

NSString *myString = @"ABCDE*FGHI-JKL"; 
NSArray *myArray = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"*-"]];
  • key 0 of myArray will contain @"ABCDE"
  • key 1 will contain @"FGHI"
  • key 2 will contain @"JKL"

Upvotes: 68

Ilahi Charfeddine
Ilahi Charfeddine

Reputation: 323

NSString *yourString = @"ABCDE*FGHI";

NSMutableArray * array = [[NSMutableArray alloc] initWithArray:[yourString componentsSeparatedByString:@"*"]];

for(int i =0 ; i < array.count ; i++){
    NSLog(@"- %d : %@ \n",i,[array objectAtIndex:i]);
}

Upvotes: 0

Gargo
Gargo

Reputation: 704

NSString *myString = @"ABCDE*FGHI";
NSArray *myArray = [myString componentsSeparatedByString:@"*"];

Upvotes: 9

luvieere
luvieere

Reputation: 37534

NSString *myString = @"ABCDE*FGHI";
NSString *subString = [myString substringWithRange: NSMakeRange(0, [myString rangeOfString: @"*"].location)];

Upvotes: 22

Related Questions