'Remove white spaces from String after formatting

I'm formatting a String from a UITextField with input type number : Example : If I have '10000', I format '10000' to have '10 000' String.

Problem : Later I need access to the Int value of this String, but when casting, I got an exception because the String is not well formatted to be casted as it contains spaces. (Example : Int("10 000") not working.)

So I want to remove spaces from the String before casting to Int, by using : myString.trimmingCharacters(in: .whitespaces) but the spaces are still here.

I'm using the following extension :

extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.groupingSeparator = " "
        formatter.numberStyle = .decimal
        return formatter
    }()
}

extension BinaryInteger {
    var formattedWithSeparator: String {
        return Formatter.withSeparator.string(for: self) ?? ""
    }
}

I also tried to retrieve the original NSNumber from my Formatter by doing :

print(Formatter.withSeparator.number(from: "10 000").intValue)

But result is nil too.

Any idea ?



Solution 1:[1]

myString.trimmingCharacters(in: .whitespaces) will remove spaces at begin and end of string, so you need to remove all spaces between characters by below code:

let newString = myString.replacingOccurrences(of: " ", with: "")

then convert newString to Int

Solution 2:[2]

Solved :

There was an additional space at the end of the strings I was using. E.g : "10 000 ", so the formatter path I was using was wrong.

Solution 3:[3]

To remove leading and trailing whitespace:

let myString = "  It Is Wednesday My Dudes! ?  "

myString.trimmingCharacters(in: .whitespaces)

print(myString) //"It Is Wednesday My Dudes! ?"

To remove all whitespaces:

extension String {
    var whiteSpaceRemoved: String {
        replacingOccurrences(of: " ", with: "")
    }
}

let myString = "  It Is Wednesday My Dudes! ?  "

print(myString.whiteSpaceRemoved) //"ItIsWednesdayMyDudes!?"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moayad Al kouz
Solution 2 AnthonyR
Solution 3