Regular expressions are your friend:
NSString * reformat( NSString * number ) { NSRegularExpression * noDigits = [ NSRegularExpression regularExpressionWithPattern: @"\\D" options: 0 error: NULL ] ; NSString * onlyDigits = [ noDigits stringByReplacingMatchesInString: number options: 0 range: NSMakeRange ( 0, number.length ) withTemplate: @"" ] ; NSRegularExpression * phoneNumberPattern = [ NSRegularExpression regularExpressionWithPattern: @"^(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d\\d)$" options: 0 error: NULL ] ; NSString * result = [ phoneNumberPattern stringByReplacingMatchesInString: onlyDigits options: 0 range: NSMakeRange( 0, onlyDigits.length ) withTemplate: @"$1-$2-$3" ] ; return result ; }
You might want to check out some alternatives to the last template change if you encounter anything other than 10 digits. Alternatively, place a length check immediately after calculating onlyDigits .
source share