2

Let's say I have this:

NSString *str = @"This is a sample string";

How will I split the string in a way that each word will be added into a NSMutableArray?

In VB.net you can do this:

Dim str As String
    Dim strArr() As String
    Dim count As Integer
    str = "vb.net split test"
    strArr = str.Split(" ")
    For count = 0 To strArr.Length - 1
        MsgBox(strArr(count))
    Next

So how to do this in Objective-C? Thanks

user1412469
  • 279
  • 5
  • 17

3 Answers3

7
NSArray *words = [str componentsSeparatedByString: @" "];

Note that words is returned as an auto-released object, so you might need to retain it, unless you are using ARC.

Also, the returned array is not mutable, so you'd need to create one yourself and initialize it with the returned array:

NSArray *words = [str componentsSeparatedByString: @" "];
NSMutableArray *mutableWords = [NSMutableArray arrayWithCapacity:[words count]];
[mutableWords addObjectsFromArray:words];

or:

NSMutableArray *mutableWords = [[str componentsSeparatedByString: @" "] mutableCopy];

This last statement returns an object that must be released as copy gives you ownership of the object.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • What if I want to split the string not only by space, but also by some characters such as comma, period, etc. How will I do this? – user1412469 Jul 04 '12 at 09:26
  • @user1412469 Simply change the `@" "` to `@","` or `@"."` etc. – trojanfoe Jul 04 '12 at 09:28
  • No what I mean is, in a single string like this `NSString *str = @"This string is separated by space, comma, and period. How to separate it?"`, how will I do this? Or do you mean that I will repeat the `NSArray *words = [str componentsSeparatedByString: ];` three times, with different components. – user1412469 Jul 04 '12 at 09:31
  • @user1412469 I'm afraid so, however you can use multiple characters in the separator string, for example `@", "`. – trojanfoe Jul 04 '12 at 09:34
  • @user1412469 You might be better of separating by space and then stripping leading and trailing commas or dots off each element in the returned array. – trojanfoe Jul 04 '12 at 09:35
1

There's an inbuilt method on NSString which splits the string based on a set of characters you pass in and returns an NSArray

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

For more, see the NSString class reference.

rounak
  • 9,217
  • 3
  • 42
  • 59
0

Working Solution. Try it out!

NSString *string = @"This is words";
NSArray *wordsArray  = [string componentsSeparatedByString:@" "];

Lets print the value of wordsArray.

NSlog(@"wordsArray value is : %@", wordsArray);

Here's the output:

wordsArray value is : (
    This,
    is,
    words
)
handiansom
  • 783
  • 11
  • 27