I have a string as shown below,
NSString * aString = @"This is the #substring1 and #subString2 I want";
How can I select only the text starting with '#' (and ends with a space), in this case 'subString1' and 'subString2'?
Note: Question was edited for clarity
Pretty simple, easy to understand version avoiding
NSRange
stuff:Assuming that you are looking to find the first string that starts with a pound, and ends with a space, this might work. I don't have XCode in front of me, so forgive me if there's a syntax error or length off by 1 somewhere:
This is what I'd do:
Then you can do what you need with the
whatYouWant
instances. If you want to know which string it is (if it's the substring 1 or 2), check the index of ofword
string in thelistOfWords
array.I hope this helps.
A general and simple code to select all the words starting with "#" in a NSString is:
if you still need the original string you can do a copy. The inline conditional is used in case your selected item is the last word
would give you substring1
You can calculate the range using:
would give you substring1
Read more: Position of a character in a NSString or NSMutableString
and
http://iosdevelopertips.com/cocoa/nsrange-and-nsstring-objects.html
Another simple solution: