Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Format phone number in NSString according to a mask

Let's say I have a random phone number in NSString that looks like @"+33142981234"

I am also getting some masks for phone number formatting from a server like these:

mask = " (###) ###-###";

What should I do to format the number according to the mask? I would like to fill in the # with the symbols from NSString. Is there any convenient way to do this in Obj-с?

Is there also a way to do it on-the-fly while the text is being entered in a UITextField?

Upvotes: 1

Views: 3321

Answers (3)

Alexey Kozhevnikov
Alexey Kozhevnikov

Reputation: 4259

You can use AKNumericFormatter library for it. It has formatter and convenient UITextField category, it's available as a cocoapod.

Upvotes: 1

Janene Pappas
Janene Pappas

Reputation: 1356

I recommend using the google libPhoneNumber library. There's a port to Objective-C here:

https://github.com/me2day/libPhoneNumber-iOS

It has all kinds of wonderful phone number parsing, formatting, validation, etc. functionality that makes phone numbers easier. I use it for all of my mobile apps.

Upvotes: 2

jhabbott
jhabbott

Reputation: 19281

Turn this into code:

create an empty destination string that you can add characters to
start at index 0 in both strings (formatIndex = numberIndex = 0)
for each character (formatChar) in the format string
{
    if formatChar is a '#'
    {
        find the next number character (numberChar)
        add numberChar to the destination string
    }
    else
    {
        copy formatChar into the destination string
    }
}

Upvotes: 0

Related Questions