john doe
john doe

Reputation: 9660

Remove special characters from the string

I am trying to use an iOS app to dial a number. The problem is that the number is in the following format:

po placeAnnotation.mapItem.phoneNumber!
"‎+1 (832) 831-6486"

I want to get rid of some special characters and I want the following:

832-831-6486

I used the following code but it did not remove anything:

let charactersToRemove = CharacterSet(charactersIn: "()+-")
var telephone = placeAnnotation.mapItem.phoneNumber?.trimmingCharacters(in: charactersToRemove)

Any ideas?

Upvotes: 4

Views: 15757

Answers (6)

Ashutosh Mishra
Ashutosh Mishra

Reputation: 1939

If you have the number and special character in String format the use following code to remove special character

let numberWithSpecialChar = "1800-180-0000" 

let actulNumber = numberWithSpecialChar.components(separatedBy: CharcterSet.decimalDigit.inverted).joined()

Otherwise, If you have the characters and special character in String format the use following code to remove special character

let charactersWithSpecialChar = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!" 

let actulString = charactersWithSpecialChar.components(separatedBy: CharacterSet.letters.inverted).joined(separator: " ")

Upvotes: 0

abc
abc

Reputation: 1

NSString *str = @"(123)-456-7890";
NSLog(@"String: %@", str);

// Create character set with specified characters
NSMutableCharacterSet *characterSet = 
  [NSMutableCharacterSet characterSetWithCharactersInString:@"()-"];

// Build array of components using specified characters as separtors
NSArray *arrayOfComponents = [str componentsSeparatedByCharactersInSet:characterSet];

// Create string from the array components
NSString *strOutput = [arrayOfComponents componentsJoinedByString:@""];

NSLog(@"New string: %@", strOutput);

Upvotes: -2

Hardik Thakkar
Hardik Thakkar

Reputation: 15951

Swift 3

func removeSpecialCharsFromString(_ str: String) -> String {
        struct Constants {
            static let validChars = Set("1234567890-".characters)
        }
        return String(str.characters.filter { Constants.validChars.contains($0) })
    }

To Use

let str : String = "+1 (832) 831-6486"
let newStr : String = self.removeSpecialCharsFromString(str)
print(newStr)

Note: you can add validChars which you want in string after operation perform.

Upvotes: 0

Vignesh
Vignesh

Reputation: 10251

I know the question is already answered, but to format phone numbers in any way one could use a custom formatter like below

class PhoneNumberFormatter:Formatter
{
  var numberFormat:String = "(###) ### ####"

  override func string(for obj: Any?) -> String? {

    if let number = obj as? NSNumber
    {
      var input = number as Int64
      var output = numberFormat
      while output.characters.contains("#")
      {
        if let range = output.range(of: "#", options: .backwards)
        {
           output = output.replacingCharacters(in: range, with: "\(input % 10)")
           input /= 10
        }
        else
        {
          output.replacingOccurrences(of: "#", with: "")
        }
      }
      return output
    }
    return nil
  }

  func string(from number:NSNumber) -> String?
  {
    return string(for: number)
  }

}


let phoneNumberFormatter = PhoneNumberFormatter()
//Digits will be filled backwards in place of hashes. It is easy change the custom formatter in anyway 
phoneNumberFormatter.numberFormat = "###-##-##-##-##"
phoneNumberFormatter.string(from: 18063783889)

Upvotes: 0

GetSwifty
GetSwifty

Reputation: 7746

If you want something similar to CharacterSet with some flexibility, this should work:

let phoneNumber = "1 (832) 831-6486"

let charsToRemove: Set<Character> = Set("()+-".characters)
let newNumberCharacters = String(phoneNumber.characters.filter { !charsToRemove.contains($0) })
print(newNumberCharacters) //prints 1 832 8316486

Upvotes: 5

Rob C
Rob C

Reputation: 366

placeAnnotation.mapItem.phoneNumber!.components(separatedBy: CharacterSet.decimalDigits.inverted)
    .joined()

Here you go!

I tested and works well.enter image description here

Upvotes: 26

Related Questions