2

Now, I'm practicing the Swift Language.

I created a StringHelper Class.

It saves a string in the str property, and by using a method, it returns same string without whitespace.

class StringHelper {

    let str:String

    init(str:String) {
        self.str = str
    }

    func removeSpace() -> String {
        //how to code
    }
}


let myStr = StringHelper(str: "hello swift")

myStr.removeSpace()//it should print  'helloswift'

I want to use only the Swift language... not the NSString methods, because I'm just practicing using Swift.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
alphonse
  • 687
  • 1
  • 6
  • 16
  • you can use this: `return str.stringByReplacingOccurrencesOfString(" ", withString: "")` at the line of `//how to code` – Dániel Nagy Aug 28 '15 at 10:55
  • 1
    @DánielNagy `stringByReplacingOccurrencesOfString` is cool but it's an NSString method. OP wants pure Swift. – Eric Aya Aug 28 '15 at 10:57
  • @EricD. you are right, that is not good in this case – Dániel Nagy Aug 28 '15 at 11:05
  • 1
    possible duplicate of [Any way to replace characters on Swift String?](http://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string) – Eric Aya Aug 28 '15 at 11:08

2 Answers2

7

Here's a functional approach using filter:

Swift 1.2:

let str = "  remove  spaces please "

let newstr = String(filter(Array(str), {$0 != " "}))
println(newstr)  // prints "removespacesplease"

Swift 2/3:

let newstr = String(str.characters.filter {$0 != " "})
print(newstr)

The idea is to break the String into an array of Characters, and then use filter to remove all Characters which are not a space " ", and then create a new string from the array using the String() initializer.


If you want to also remove newlines "\n" and tabs "\t", you can use contains:

Swift 1.2:

let newstr = String(filter(Array(str), {!contains([" ", "\t", "\n"], $0)}))

Swift 2/3:

let newstr = String(str.characters.filter {![" ", "\t", "\n"].contains($0)})
weakish
  • 28,682
  • 5
  • 48
  • 60
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

A more generic version of this questions exists here, so here's an implementation of what you're after:

func removeSpace() -> String {
    let whitespace = " "
    let replaced = String(map(whitespace.generate()) {
        $0 == " " ? "" : $0
    })
    return replaced
}

If you prefer brevity:

func removeSpace() -> String {
    return String(map(" ".generate()) { $0 == " " ? "" : $0 })
}

Or, if you're using Swift 2:

func removeSpace() -> String {
    let whitespace = " "
    let replaced = String(whitespace.characters.map {
        $0 == " " ? "" : $0
    })
    return replaced
}

Again, more concisely:

func removeSpace() -> String {
    return String(" ".characters.map { $0 == " " ? "" : $0 })
}
Community
  • 1
  • 1
pxlshpr
  • 986
  • 6
  • 15