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.

4
  • you can use this: return str.stringByReplacingOccurrencesOfString(" ", withString: "") at the line of //how to code Commented Aug 28, 2015 at 10:55
  • 1
    @DánielNagy stringByReplacingOccurrencesOfString is cool but it's an NSString method. OP wants pure Swift. Commented Aug 28, 2015 at 10:57
  • @EricD. you are right, that is not good in this case Commented Aug 28, 2015 at 11:05
  • 1
    possible duplicate of Any way to replace characters on Swift String? Commented Aug 28, 2015 at 11:08

2 Answers 2

8

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)})
Sign up to request clarification or add additional context in comments.

Comments

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 })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.