# Combining strings

```let aString = "Hello"

// Let's play with strings today

// we can combine strings using the + operator

let newString = aString + " swift lovers" // "Hello swift lovers"

// string interpolaton can also be used to combine strings
let a = "BAT"
let b = "MAN"

println("\(a) + \(b) = \(a + b)")
// BAT + MAN = BATMAN
```

We have an array with animal names. Let’s combine all the names in one string separated by commas.

```let animals = ["cat", "dog", "turtle", "swift", "elephant"]

// Solution 1

var result: String = ""
for animal in animals {
if countElements(result) > 0 {
result += ","
}
result += animal
}
// result is "cat,dog,turtle,swift,elephant"

// Solution 2

println("a list of animals: " + ",".join(animals))
// a list of animals: cat,dog,turtle,swift,elephant

// or we can get fancy and print an unordered list

println("\n".join(animals.map({ "• " + \$0})))

//• cat
//• dog
//• turtle
//• swift
//• elephant

// We can make the list capitalized

let capitalizedAnimals = animals.map({ \$0.capitalizedString })

println("\n".join(capitalizedAnimals.map({ "• " + \$0})))

//• Cat
//• Dog
//• Turtle
//• Swift
//• Elephant

// And sorted

let sortedAnimals = capitalizedAnimals.sorted({ (first, second) -> Bool in
return first < second
})

println("\n".join(sortedAnimals.map({ "• " + \$0})))

//• Cat
//• Dog
//• Elephant
//• Swift
//• Turtle

```

In Swift you can’t multiply a `String` with a scalar, but you can define operators. Let’s make `"cat" * 3` work.

```func *(string: String, scalar: Int) -> String {
let array = Array(count: scalar, repeatedValue: string)
return "".join(array)
}

println("cat " * 3 + "dog " * 2)
// cat cat cat dog dog
```

This operator looks helpful if you want to indent your output. Let’s look at how we can show a binary tree.

```// A binary tree of order 1 is just one node
// A binary tree of order > 1 has one node in the middle
// and two binary trees one order smaller before and after

func printTree(height: Int, padding: Int) {
if height == 1 {
println("   " * padding + "*")
} else {
printTree(height - 1, padding + 1)
println("   " * padding + "*")
printTree(height - 1, padding + 1)
}
}

printTree(5, 0)

//            *
//         *
//            *
//      *
//            *
//         *
//            *
//   *
//            *
//         *
//            *
//      *
//            *
//         *
//            *
//*
//            *
//         *
//            *
//      *
//            *
//         *
//            *
//   *
//            *
//         *
//            *
//      *
//            *
//         *
//            *

```

## Working with characters

A quick reminder, you can use `lowercaseString` and `uppercaseString` to create a new string in which all the letters are lowercase or uppercase.

``````let name = "We ❤ Swift"

let lowercase = name.lowercaseString // "we ❤ swift"
let uppercase = name.uppercaseString // "WE ❤ SWIFT"

``````

Let’s take a simple challenge. Given a string create a new one with all the characters in reverse order.

```var inReverse = ""

for letter in "We ❤ Swift" {
println(letter)
inReverse = "\(letter)" + inReverse
}

println(inReverse)
// "tfiwS ❤ eW"
```

Given a string make all the vowels uppercase.

```var bigVoewls = ""
for c in "Let's make all the vowels in this string upper case!" {
case "a", "e", "i", "o", "u":
default:
break
}
}

println(bigVoewls)
// LEt's mAkE All thE vOwEls In thIs strIng UppEr cAsE!
```

Given a list of names (like your contect list) and a string, find all the names that start with that string.

```let contacts = ["Alec", "Annalee", "Anya", "Arlie", "Blaine", "Burton", "Cecily", "Deana",
"Deirdre", "Elena", "Elodia", "Francina", "Freeman", "Herbert", "Iona", "Jacqui", "Janna",
"Jeneva", "Karla", "Katelin", "Kathaleen", "Kesha", "Kum", "Lilliam", "Mardell", "Margarite",
"Margy", "Marta", "Maryalice", "Mellisa", "Melodee", "Miguel", "Millie", "Myong", "Nakita",
"Nancy", "Nicolasa", "Noemi", "Roselia", "Sade", "Shalonda", "Shawn", "Siobhan", "Tanna",
"Thu", "Vanesa", "Vonnie", "Wade", "Winford", "Xiomara"]

let prefix = "ma"

// Case sensitive
contacts.filter({ contact in
contact.hasPrefix(prefix)
})
// has 0 matches

// Case unsensitive
let lowercasePrefix = prefix.lowercaseString

contacts.filter({ contact in
contact.lowercaseString.hasPrefix(lowercasePrefix)
})
// has 5 matches -> "Mardell", "Margarite", "Margy", "Marta", "Maryalice"

```

Find the state that has the state that has the most vowels in its name. To make things simple we are going to assume that y is not a voewl

```let states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "MaineME", "Maryland", "Massachuset", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "NevadaNV", "New Hampshi", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "District of Columbia"]

func numberOfVowels(string: String) -> Int {
var nVowels = 0
for ch in string {
switch "\(ch)".lowercaseString {
case "a", "e", "i", "o", "u":
nVowels++
default:
break
}
}
return nVowels
}

let theStateWithMostVowles = states.reduce(("", 0), combine: { (res, state) in
let (best, count) = res
let nVowels = numberOfVowels(state)
if nVowels > count {
return (state, nVowels)
} else {
return (best, count)
}
})
```

`District of Columbia` is the state with the most vowels. How about the state with the most consecutive consonants.

```func maxConsecutiveConsonants(string: String) -> Int {
var best = 0
var current = 0
for ch in string {
switch "\(ch)".lowercaseString {
case "a", "e", "i", "o", "u":
if current > best {
best = current
}
current = 0
default:
current++
break
}
}
if current > best {
best = current
}
return best
}

let theStateWithMostConsecutiveConsonants = states.reduce(("", 0), combine: { (res, state) in
let (best, count) = res
let nVowels = maxConsecutiveConsonants(state)
if nVowels > count {
return (state, nVowels)
} else {
return (best, count)
}
})```
(1 votes, average: 5.00 out of 5)

## 6 comments for “Playing with Strings”

1. Bob
September 28, 2014 at 2:18 am

Nice article.
let sortedAnimals = capitalizedAnimals.sorted({ (first, second) -> Bool in
return first < second
can also be simplified as
let sortedAnimals = capitalizedAnimals.sorted(<)

• Rhywun
September 30, 2014 at 2:05 am

Nice! I haven’t seen that one before. I only got it as short as

let sortedAnimals = animals.sorted { \$0 < \$1 }

2. shoody
March 7, 2016 at 12:41 pm

let aString = “Hello”

// Let’s play with strings today

// we can combine strings using the + operator

let newString = str + ” swift lovers” // “Hello swift lovers”

where is “str”? It should be “aString”

• March 11, 2016 at 10:53 am

Thank you!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)