Deepak Khiwani
Deepak Khiwani

Reputation: 744

Remove white space from contact number fetched from phone book

I know its a very basic question, but I am stuck at this point.

I am fetching contact numbers from phonebook and having them in an array.

And then fetching a particular one from array in NSString

And I am trying to remove white space from the number, but it is not actually with the below written codes:

NSString *num = @"+44 123 456 7890";

num = [num stringByReplacingOccurrencesOfString:@" " withString:@"0"];

**OR**

num = [num stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Please let me know what I need to do to remove this space.

Thanks

EDIT

NSString *num = [contactNumbers objectAtIndex:i];
        num = [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
        num = [num stringByReplacingOccurrencesOfString:@" " withString:@""];
        num = [num substringFromIndex:[num length]-10];

Upvotes: 2

Views: 2652

Answers (2)

Deepak Khiwani
Deepak Khiwani

Reputation: 744

Done the trick :

NSString * strippedNumber = [num stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];

Upvotes: 14

Rick
Rick

Reputation: 1818

Try this:

// Replace @"0" with @""
num = [num stringByReplacingOccurrencesOfString:@" " withString:@""];

Using stringByTrimmingCharactersInSet only trims white spaces from the beginning and end of string.

EDIT

NSString *num = [contactNumbers objectAtIndex:i];
NSString *newString = [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
newString = [newString substringFromIndex:[num length]-10];

Upvotes: 1

Related Questions