Reputation: 717
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.
Upvotes: 2
Views: 2781
Reputation: 154603
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 Character
s, and then use filter
to remove all Character
s 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)})
Upvotes: 8
Reputation: 1111
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 })
}
Upvotes: 0