0

I need to split NSString to array by specific word.

I've tried to use [componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]]

But the split is performed by a single character, and I need a few chars.

Example:

NSString @"Hello great world";

Split key == @" great ";

result:

array[0] == @"Hello";
array[1] == @"world";
Asi Givati
  • 1,348
  • 1
  • 15
  • 31

3 Answers3

1

Try

NSString *str = @"Hello great world"; 
//you can use the bellow line to remove space   
//str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];       
// split key = @"great"

NSArray *arr = [str componentsSeparatedByString:@"great"];
Jamil
  • 2,977
  • 1
  • 13
  • 23
  • unfortunately, no one is reading the question carefully, what is the requirment – Jamil Oct 19 '15 at 07:38
  • 1
    but in this answer , u get the array[1] == @" world"; not like array[1] == @"world";, how would u say this is correct man – Anbu.Karthik Oct 19 '15 at 07:49
  • @Anbu.Karthik - Well spotted. I think that was just a simple typo, fixed it for them. – CRD Oct 19 '15 at 08:57
  • or simply you can avoid white spaces – Jamil Oct 19 '15 at 09:00
  • This is still a bit naive solution. What if the word is the last word? E.g. "That's great." The best solution would probably be using a regular expression. This will work for simple cases but won't work in general. – Sulthan Oct 19 '15 at 09:01
0

Code:

NSString *string = @"Hello great world";
NSArray *stringArray = [string componentsSeparatedByString: @" great "];

NSLog(@"Array 0: %@" [stringArray objectAtIndex:0]);
NSLog(@"Array 1: %@" [stringArray objectAtIndex:1]);
Ty Lertwichaiworawit
  • 2,950
  • 2
  • 23
  • 42
0

The easiest way is the following:

NSString *string = @"Hello Great World";

NSArray *stringArray = [string componentsSeparatedByString: @" "];

This can help you.

iPeter
  • 1,330
  • 10
  • 26