string replace phone number iOS swift - ios

I import a phone-number from "Contacts" and save in NSString.
this string contains white-space and I try to delete them using the method:
numero = numero.stringByReplacingOccurrencesOfString(" ", withString: "")
this method doesn't work.
func sostituisci( stringa: NSString! ) -> NSString
{
var numero: NSString = ""
NSLog(stringa)
numero = ((stringa as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString)
NSLog(numero)
return numero
}
the output unchanged
log
2014-11-05 17:54:50.734 HappyRicarica[33438:3119446] (327) 124-3503
2014-11-05 17:54:50.737 HappyRicarica[33438:3119446] (327) 124-3503

I suspect that the space character in your string is not really a space. Try adding this after NSLog(string) to see what the unicode scalar values are for the characters in your string:
for uni in (stringa as String).unicodeScalars {
println("\(uni) = \(uni.value)")
}
The expected output for "(327) 124-3503" is:
( = 40
3 = 51
2 = 50
7 = 55
) = 41
= 32
1 = 49
2 = 50
4 = 52
- = 45
3 = 51
5 = 53
0 = 48
3 = 51
From your comment, your space has value 160 instead of 32. You could remove that with:
numero = stringa.stringByReplacingOccurrencesOfString(String(Character(UnicodeScalar(160))), withString: "")

update: Xcode 7.2 • Swift 2.1.1
extension String {
var numbersOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890")
.invertedSet)
.joinWithSeparator("")
}
var numbersExempt: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890"))
.joinWithSeparator("")
}
var charactersOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet).joinWithSeparator("")
}
var charactersExempt: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")).joinWithSeparator("")
}
func keep(keepIt: String) -> String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: keepIt).invertedSet).joinWithSeparator("")
}
func exclude(excludeIt: String) -> String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: excludeIt)).joinWithSeparator("")
}
}
let phoneNumber = "+1 (555) 555 - 5555".numbersOnly
print(phoneNumber) // "15555555555"
let excludePlusMinus = "+1 (555) 555-5555".exclude("+-") // "1 (555) 5555555"
let keepWhatever = "+1 (555) 555-5555".keep("()-+") // "+()-"
you can also use your function to subtract only spaces with some adjustments. Try like this:
func sostituisci(stringa: String) -> String {
return stringa.stringByReplacingOccurrencesOfString(" ", withString: "")
}
sostituisci("1 234 567 8901") // "12345678901"
or like an extension:
extension String {
var sostituisci: String {
return stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
let phoneNumber2 = "1 234 567 8901".sostituisci

NSString is not String, so you should use:
numero = ((numero as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString)

did you try :
let str = "XX XX XX XX XX"
let separated = str.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let finalStr = "".join(separated)

Related

How can I change a UILabel into a number programmatically? [duplicate]

I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
Converting Int to String:
let x : Int = 42
var myString = String(x)
And the other way around - converting String to Int:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Here are 4 methods:
var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description
I can imagine that some people will have an issue with ss. But if you were looking to build a string containing other content then why not.
In Swift 3.0:
var value: Int = 10
var string = String(describing: value)
Swift 4:
let x:Int = 45
let str:String = String(describing: x)
Developer.Apple.com > String > init(describing:)
The String(describing:) initializer is the preferred way to convert an instance of any type to a string.
Custom String Convertible
Just for completeness, you can also use:
let x = 10.description
or any other value that supports a description.
Swift 4:
Trying to show the value in label without Optional() word.
here x is a Int value using.
let str:String = String(x ?? 0)
To save yourself time and hassle in the future you can make an Int extension. Typically I create a shared code file where I put extensions, enums, and other fun stuff. Here is what the extension code looks like:
extension Int
{
func toString() -> String
{
var myString = String(self)
return myString
}
}
Then later when you want to convert an int to a string you can just do something like:
var myNumber = 0
var myNumberAsString = myNumber.toString()
in swift 3.0 this is how we can convert Int to String and String to Int
//convert Integer to String in Swift 3.0
let theIntegerValue :Int = 123 // this can be var also
let theStringValue :String = String(theIntegerValue)
//convert String to Integere in Swift 3.0
let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
for whatever reason the accepted answer did not work for me. I went with this approach:
var myInt:Int = 10
var myString:String = toString(myInt)
Multiple ways to do this :
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
let intAsString = 45.description // "45"
let stringAsInt = Int("45") // 45
Swift 2:
var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)
Swift String performance
A little bit about performance
UI Testing Bundle on iPhone 7(real device) with iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
iam using this simple approach
String to Int:
var a = Int()
var string1 = String("1")
a = string1.toInt()
and from Int to String:
var a = Int()
a = 1
var string1 = String()
string1= "\(a)"
Convert Unicode Int to String
For those who want to convert an Int to a Unicode string, you can do the following:
let myInteger: Int = 97
// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
return ""
}
// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)
// results
print(myString) // a
Or alternatively:
let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
let myString = String(myUnicodeScalar)
}
I prefer using String Interpolation
let x = 45
let string = "\(x)"
Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions
let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
exampleLabel.text = String(yourInt)
To convert String into Int
var numberA = Int("10")
Print(numberA) // It will print 10
To covert Int into String
var numberA = 10
1st way)
print("numberA is \(numberA)") // It will print 10
2nd way)
var strSomeNumber = String(numberA)
or
var strSomeNumber = "\(numberA)"
let a =123456888
var str = String(a)
OR
var str = a as! String
In swift 3.0, you may change integer to string as given below
let a:String = String(stringInterpolationSegment: 15)
Another way is
let number: Int = 15
let _numberInStringFormate: String = String(number)
//or any integer number in place of 15
If you like swift extension, you can add following code
extension Int
{
var string:String {
get {
return String(self)
}
}
}
then, you can get string by the method you just added
var x = 1234
var s = x.string
let Str = "12"
let num: Int = 0
num = Int (str)

How to replace Email id text before # with * in swift 3.0

Hello I have not get perfect solution for how to replace Email Id text before # with * like
suppose my email id is XXXXXXX#gmail.com then my output I want like *******#gmail.com
I try like this
let delimiter = "#"
let newstr = "Himmoradiya#gmail.com"
var token = newstr.components(separatedBy: delimiter)
let newQuery = (token[0] as NSString).replacingCharacters(
in: NSMakeRange(0,token[0].characters.count), with: "*")
Any suggestion is accepted.
Thank you.
Use init(repeating:count:)
let newstr = "Himmoradiya#gmail.com"
var token = newstr.components(separatedBy: "#")
let newQuery = String(repeating: "*", count: token[0].characters.count) //check array length before using index
print(newQuery + "#" + token[1] ) // *******#gmail.com
Write this code:
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: "#", with: "*")
Use this function .
func getStarred(_ email : String ) -> String
{
var didFoundATRO = false
var tempString = ""
for char in email.characters
{
if char == "#"
{
didFoundATRO = true
}
if !didFoundATRO
{
tempString += "*"
}
else
{
tempString.append(char)
}
}
return tempString
}
You can do like,
let delimiter = "#"
let newstr = "Himmoradiya#gmail.com"
let arr = newstr.components(separatedBy: delimiter)
let resultStr = "xxxxxx" + "#" + arr[1]
print(resultStr)
let delimiter = "#"
var newstr = "Himmoradiya#gmail.com"
let arr = newstr.components(separatedBy: delimiter)
let strMail = arr.first!
let strReplaceStr = String(repeating: "*", count: strMail.characters.count)
newstr = newstr.replacingOccurrences(of: strMail, with: strReplaceStr)
and output (newstr) will be : ***********#gmail.com
I have created a string extension like...
extension String {
var hideEmailPrefix: String {
if self.contains("#") {
var part = self.components(separatedBy: "#")
let newText = String(repeating: "*", count: part[0].count)
return newText + "#" + part[1]
}
return self
}
}
Then in my ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let email = "abc#gmail.com"
print(email.hideEmailPrefix) // ***#gmail.com
}
var maskEmail: String {
let email = self
let components = email.components(separatedBy: "#")
var maskEmail = ""
if let first = components.first {
maskEmail = String(first.enumerated().map { index, char in
return [0, 1, first.count - 1, first.count - 2].contains(index) ?
char : "*"
})
}
if let last = components.last {
maskEmail = maskEmail + "#" + last
}
return maskEmail
}
var maskPhoneNumber: String {
return String(self.enumerated().map { index, char in
return [0, 3, self.count - 1, self.count - 2].contains(index) ?
char : "*"
})
}

Swift3 convert string value to hexadecimal string

I am new to Swift and I want to convert a string into hexadecimal string. I have found a Objective-C function to a string into hexadecimal.
NSString * str = #"Say Hello to My Little Friend";
NSString * hexString = [NSString stringWithFormat:#"%#",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
for (NSString * toRemove in [NSArray arrayWithObjects:#"<", #">", #" ", nil])
hexString = [hexString stringByReplacingOccurrencesOfString:toRemove withString:#""];
NSLog(#"hexStr:%#", hexString);
Now I am unable to convert this function in Swift. Currently I am using Swift3.
Please someone can do this for me?
This produces the same output as the ObjC version
let str = "Say Hello to My Little Friend"
let data = Data(str.utf8)
let hexString = data.map{ String(format:"%02x", $0) }.joined()
Details
Xcode 11.2.1 (11B500), Swift 5.1
Solution
extension String {
func toHexEncodedString(uppercase: Bool = true, prefix: String = "", separator: String = "") -> String {
return unicodeScalars.map { prefix + .init($0.value, radix: 16, uppercase: uppercase) } .joined(separator: separator)
}
}
Usage
let str = "Hello, playground"
print(str.toHexEncodedString()) // 48656C6C6F2C20706C617967726F756E64
print(str.toHexEncodedString(uppercase: false, prefix: "0x", separator: " ")) // 0x48 0x65 0x6c 0x6c 0x6f 0x2c 0x20 0x70 0x6c 0x61 0x79 0x67 0x72 0x6f 0x75 0x6e 0x64
Convert your string to NSData like this.
let myString = "ABCDEF"
let data = myString.dataUsingEncoding(NSUTF8StringEncoding)
Then convert the NSData to hexadecimal string using following method -
func hexFromData(data:NSData) -> String {
let p = UnsafePointer<UInt8>(data.bytes)
let len = data.length
var str: String = String()
for i in 0...len-1 {
str += String(format: "%02.2X", p[i])
}
return str
}
Hope this helped.
Please try this,
let string = "Say Hello to My Little Friend"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
print(data)
and its output is:
Optional(<53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>)
Swift 3
let string = "Hello World!"
let data = string.data(using: String.Encoding.utf8)
let hexString = data?.hex
extension Data {
var hex: String {
var string = ""
#if swift(>=3.1)
enumerateBytes { pointer, index, _ in
for i in index..<pointer.count {
string += String(format: "%02x", pointer[i])
}
}
#else
enumerateBytes { pointer, count, _ in
for i in 0..<count {
string += String(format: "%02x", pointer[i])
}
}
#endif
return string
}
}

Replace numeric of different length in a string with different text length

Problem: Numeric is of different length could be 1, 200, 1000, 39 99995 etc. And need to replace with a text eg. "Apple" which is of different lenth comapring to the numeric values.
let str: String = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"
Expected Result = "hello i have Apple object of Apple string class with Apple object, similar to Apple errors"
I have tried with below code:
var originalString: String = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"
let strippedString: NSMutableString = NSMutableString(capacity: originalString.characters.count)
var numArray: [String] = []
var locArray: [NSNumber] = []
var scanner: NSScanner = NSScanner(string:originalString)
let numbers: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
while scanner.atEnd == false {
var buffer: NSString?
if scanner.scanCharactersFromSet(numbers, intoString: &buffer) {
strippedString.appendString(buffer! as String)
numArray.append(buffer! as String)
locArray.append(scanner.scanLocation)
}
else {
scanner.scanLocation = (scanner.scanLocation + 1)
}
}
for (index, _) in numArray.enumerate() {
var loc : Int = Int(locArray[index] ) - (String(numArray[index]).characters.count)
let len = String(numArray[index]).characters.count
let dupStr = "Apple"
if(index != 0 && len != dupStr.characters.count)
{
loc = loc + (dupStr.characters.count - len) + 1
}
originalString.replaceRange(originalString.startIndex.advancedBy(loc)..<originalString.startIndex.advancedBy(loc + len), with: dupStr)
}
print(originalString)
Swift 2
NSScanner is great, but if you want a simpler solution for this task, you could use componentsSeparatedByString, map, Int() and joinWithSeparator, like this:
let originalString = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"
let tokens = originalString.componentsSeparatedByString(" ")
let newTokens = tokens.map { (token) -> String in
if let _ = Int(token) {
return "Apple"
}
return token
}
let result = newTokens.joinWithSeparator(" ")
print(result)
Prints:
hello i have Apple object of Apple string class with Apple object, similar to Apple errors
There's also a short version for the mapping:
let newTokens = tokens.map { Int($0) != nil ? "Apple" : $0 }
Swift 3
componentsSeparatedByString(_:) is now components(separatedBy:), and joinWithSeparator(_:) is now joined(separator:).
let tokens = originalString.components(separatedBy: " ")
let newTokens = tokens.map { Int($0) != nil ? "Apple" : $0 }
let result = newTokens.joined(separator: " ")
var str: String = "hello i have 1313 object of 10 string class with 1 object, similar to 9999 errors"
var comp: [AnyObject] = [AnyObject](array: str.componentsSeparatedByString(" "))
for var i = 0; i < comp.count; i++ {
var numberRegex: NSRegularExpression = NSRegularExpression.regularExpressionWithPattern("^[0-9]", options: NSRegularExpressionCaseInsensitive, error: nil)
var regexMatch: Int = numberRegex.numberOfMatchesInString(comp[i], options: 0, range: NSMakeRange(0, (String(comp[i])).length))
if regexMatch != 0 {
comp[i] = "Apple"
}
}
var result: String = comp.componentsJoinedByString(" ")
print(result)

Get the initials from a name and limit it to 2 initials

I have a the following name: John Fitzgerald Kennedy.
To get its initials, I created a method:
extension String {
public var first: String {
return String(self[startIndex])
}
}
let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.reduce("") { $0 + $1.first }
The output is : JFK
Is there an elegant way with my method (with reduce) to limit those initials to JK only, removing then the letter in the middle?
If you target iOS 9 and above:
let formatter = PersonNameComponentsFormatter()
if let components = formatter.personNameComponents(from: name) {
formatter.style = .abbreviated
return formatter.string(from: components)
}
Swift 2.0
How about this:
let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.reduce("") { ($0 == "" ? "" : $0.first) + $1.first}
That will also take care of the case where the name has no middle name or more than 1 middle name.
Swift 3
let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.characters.first!)") + "\($1.characters.first!)" }
Swift 4
let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }
Swift 4, little bit of extra work, but using PersonNameComponentsFormatter.
// Note: We Account for name suffix ( Example: III, II, Jr, Sr ) or prefixes ( Mr, Mrs )
let fullName = “Mr John Jacob Smith III”
let formatter = PersonNameComponentsFormatter()
guard let personNameComponents = formatter.personNameComponents(from: fullName) else {
return ""
}
return personNameComponents.initials
// Note: Also create Extension for PersonNameComponents
// PersonNameComponents+Initials.swift
import Foundation
extension PersonNameComponents {
var fullName: String {
return [givenName, middleName, familyName].compactMap{ $0 }.joined(separator: " ")
}
var fullNameWithSuffix: String {
return [givenName, middleName, familyName, nameSuffix].compactMap{ $0 }.joined(separator: " ")
}
var initials: String {
let firstName = givenName?.first ?? Character(" ")
let lastName = familyName?.first ?? Character(" ")
return "\(firstName)\(lastName)".trimmingCharacters(in: .whitespaces)
}
// Note: If You need first, middle, last
/*
var initials: String {
let firstName = givenName?.first ?? Character(" ")
let middleName = middleName?.first ?? Character(" ")
let lastName = familyName?.first ?? Character(" ")
return "\(firstName)\(middleName)\(lastName)".trimmingCharacters(in: .whitespaces)
}
*/
}
This is my solution.
Swift 5
extension String {
var initials: String {
return self.components(separatedBy: " ")
.reduce("") {
($0.isEmpty ? "" : "\($0.first?.uppercased() ?? "")") +
($1.isEmpty ? "" : "\($1.first?.uppercased() ?? "")")
}
}
}
extension String {
var initials: String {
return self.components(separatedBy: " ").filter { !$0.isEmpty }.reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }
}
}
This fixes the crashing problem on Guy Daher's solution.
Enumerate and filter by odd index
let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.enumerate()
.filter { (index, _) -> Bool in return index % 2 == 0 }
.reduce("") { a, i in return a + i.element.first }
Note: This one is not care about no middle name or more than one

Resources