Maria Zverina
Maria Zverina

Reputation: 11173

What's the best way to convert String into [Character] in Swift?

I would like to run a filter on a string. My first attempt failed as string is not automagically converted to Character[].

var s: String = "abc"
s.filter { $0 != "b" }

If I clumsily convert the String to Character[] with following code, it works as expected. But surely there has to be a neater way?

var cs:Character[] = []
for c in s {
    cs =  cs + [c]
}

cs = cs.filter { $0 != "b" }

println(cs)

Upvotes: 1

Views: 2728

Answers (4)

Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

String conforms to the CollectionType protocol, so you can pass it directly to the function forms of map and filter without converting it at all:

let cs = filter(s) { $0 != "f" }

cs here is an Array of Characters. You can turn it into a String by using the String(seq:) initializer, which constructs a String from any SequenceType of Characters. (SequenceType is a protocol that all lists conform to; for loops use them, among many other things.)

let filteredString = String(seq: cs)

Of course, you can just as easily put those two things in one statement:

let filteredString = String(seq: filter(s) { $0 != "f" })

Or, if you want to make a convenience filter method like the one on Array, you can use an extension:

extension String {
    func filter(includeElement: Character -> Bool) -> String {
        return String(seq: Swift.filter(self, includeElement))
    }
}

(You write it "Swift.filter" so the compiler doesn't think you're trying to recursively call the filter method you're currently writing.)

As long as we're hiding how the filtering is performed, we might as well use a lazy filter, which should avoid constructing the temporary array at all:

extension String {
    func filter(includeElement: Character -> Bool) -> String {
        return String(seq: lazy(self).filter(includeElement))
    }
}

Upvotes: 7

Pedro Varela
Pedro Varela

Reputation: 2425

The easiest way to convert a char to string is using the backslash (), for example I have a function to reverse a string, like so.

var identityNumber:String = id
for char in identityNumber{
    reversedString = "\(char)" + reversedString
}

Upvotes: 0

Mohsen
Mohsen

Reputation: 65785

You can use this syntax:

var chars = Character[]("abc")

I'm not 100% sure if the result is an array of Characters or not but works for my use case.

var str = "abc"

var chars = Character[](str)

var result = chars.map { char in "char is \(char)" }

result

Upvotes: 2

drewag
drewag

Reputation: 94723

I don't know of a built in way to do it, but you could write your own filter method for String:

extension String {
    func filter(f: (Character) -> Bool) -> String {
        var ret = ""
        for character in self {
            if (f(character)) {
                ret += character
            }
        }
        return ret
    }
}

If you don't want to use an extension you could do this:

Array(s).filter({ $0 != "b" }).reduce("", combine: +)

Upvotes: 1

Related Questions