Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 200
cannyboy Avatar asked Jun 16 '10 09:06

cannyboy


2 Answers

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"
like image 135
Samuel De Backer Avatar answered Oct 01 '22 05:10

Samuel De Backer


NSString *myString = @"ABCDE*FGHI";
NSString *subString = [myString substringWithRange: NSMakeRange(0, [myString rangeOfString: @"*"].location)];
like image 32
luvieere Avatar answered Oct 01 '22 04:10

luvieere