Search code examples
objective-cnsstringfoundation

split NSString using componentsSeparatedByString


I have a string I need to split. It would be easy using componentsSeparatedByString but my problem is that the separator is a comma but I could have commas that aren't separator.

I explain:

My string:

NSString *str = @"black,red, blue,yellow";

the comma between red and blue must not be considered as separator.

I can determine if comma is a separator or not checking if after it there is a white space.

The goal is to obtain an array with:

(
black,
"red, blue",
yellow
)

Solution

  • This is tricky. First replace all occurences of ', ' (comma+space) with say '|' then use components separated method. Once you are done, again replace '|' with ', ' (comma+space).