简体   繁体   English

从字符串中删除特殊字符

[英]Remove special characters from the string

I am trying to use an iOS app to dial a number.我正在尝试使用 iOS 应用程序拨打号码。 The problem is that the number is in the following format:问题是数字格式如下:

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

I want to get rid of some special characters and I want the following:我想摆脱一些特殊字符,我想要以下内容:

832-831-6486 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?有任何想法吗?

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

Here you go!干得好!

I tested and works well.我测试过并且运行良好。 在此处输入图片说明

If you want something similar to CharacterSet with some flexibility, this should work:如果你想要一些类似于 CharacterSet 的东西具有一定的灵活性,这应该可行:

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

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)

Swift 3斯威夫特 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.注意:您可以在操作执行后在字符串中添加您想要的validChars。

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: " ")
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM