CocoaCodeSnippet: Split NSString on Space or Line Break
I’m starting a new section on my blog: CocoaCodeSnippets. Whenever I run into some interesting code or write a little short method that seems useful, I’m going to post a short little explanation and share the code. For my first CocoaCodeSnippet, I wanted to pose a solution to a problem that might have a better answer. I have an NSTextView, and I’m getting its contents. I want to itterate over each word, so you would think:
1 | NSArray *words = [theString componentsSeparatedByString:@" "]; |
But this fails when the user enters a line break or paragraph. I wrote this code instead to get around that problem and truly break a string into words:
1 2 3 4 5 6 7 | NSMutableArray *words = [[NSMutableArray alloc] init]; NSArray *lines = [theString componentsSeparatedByString:@"\n"]; NSEnumerator *enumerator = [lines objectEnumerator]; id obj; while(obj = [enumerator nextObject]) { [words addObjectsFromArray:[obj componentsSeparatedByString:@" "]]; } |
This suffices for now. My only concern is if there are \r or other variations for line breaks. This code will not take those into account. For now, I’m satisifed with this solution, but if you have a better way, please post in the comments.
-
morimura
-
Ben



