Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Loop through integers in string and replace with remove

I would like to remove all numbers (Integers) in a string and remove them.

I would like to use

stringByReplacingOccurrencesOfString:@"1" withString:@""];

E.g.

NSString *myString = @"Hello 1 what 2 is 3 the 4 time5"

will become

NSString *myString = @"Hello what is the time"

1 Answer

There's a couple of way to do this. Using the approach you want, it would look something like this:

myString = [myString stringByReplacingOccurrencesOfString:@"[0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, myString.length)];

This goes through the entire string looking for the numbers 0 through 9, represented as a regular expression above - [0-9], and deletes them. But, deleting the characters only will leave you with two spaces between each word. If you don't mind that it's ok, but if you do, you have to replace them with a single space:

myString = [myString stringByReplacingOccurrencesOfString:@" " withString:@" "];

This is probably not the cleanest way to remove extra spaces from a string, but it does produce the output you are looking for. I hope it helps.

Excellent. Thank you for your help!