> ## Content Index
> Fetch the complete content index at: https://developerinsider.co/llms.txt
> Use this file to discover other available public pages before exploring further.

# String by Example - Swift Programming Language
- URL: https://developerinsider.co/string-by-example-swift-programming-language/
- Published: 2017-08-25T11:49:51.000Z
- Updated: 2022-08-05T04:44:50.000Z
- Author: Guest
- Tags: Swift, iOS, Swift4

## Overview

A string literal is a sequence of characters surrounded by double quotes (").

## 1\. Creating and Initializing Strings

#### 1.1 Initializing Strings

```swift
let name = "vineeta"
print(name)

```

- String interpolations are string literals that evaluate any included expressions and convert the results to string form.
- String interpolations give you an easy way to build a string from multiple pieces.
- Wrap each expression in a string interpolation in parentheses, prefixed by a backslash.

```swift
let name = "Vineeta"
print( "Welcome, \(name)!")

```

#### 1.2 Initializing Multiline string

- Multiline string literals are enclosed in three double quotation marks ("""), with each delimiter on its own line.
- Indentation is stripped from each line of a multiline string literal to match the indentation of the closing delimiter.

```swift
let banner = """
          __,
         (          o   /) _/_
          `.  , , , ,  //  /
        (___)(_(_/_(_ //_ (__
                     /)
                    (/
        """
print(banner)

```

#### 1.3 Initializing an Empty String

```swift
var emptyString = ""               
var anotherEmptyString = String()  
var anotherOneEmptyString: String

let newString = String()

```

## 2\. Modifying and Comparing Strings

- Strings always have value semantics. Modifying a copy of a string leaves the original unaffected.

#### 2.1 Strings can be combined using the concatenation operator (+).

```swift
let name : String = "Vineeta"
let greetMsg =  name + " We're glad you're here!"
print(greetMsg)                 

//prints Vineeta We're glad you're here!

```

#### 2.2 String Mutability

- String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), or to a constant (in which case it cannot be modified).

```swift
var variableString = "Horse"
variableString += " and carriage"
print(variableString)

```

#### 2.3 Compairing String

- Comparing strings for equality using the equal-to operator (==) or a relational operator (like < or >=).

```swift
let cafe1 = "Cafe\u{301}"
let cafe2 = "Café"
print(cafe1 == cafe2)

```

## 3\. Measuring the Length of a String

- A single string can have greatly differing lengths when measured by its different views.

```swift
let name = "Vineeta"
print(name.count)                            // prints 7
print(name.utf8.count)                       // prints 7 
print(name.utf16.count)                      // prints 7
print(name.unicodeScalars.count)             // prints 7

```

## 4\. Inspecting a String - isEmpty

```swift
let name = "Vineeta"
if name.isEmpty{
	print("empty tag ")
}else{
	print("Name: \(name)")
}
// prints Name:Vineeta

```

## 5\. Changing Case

#### 5.1 uppercase

```swift
var name = "Vineeta"
print(name.uppercased())
//prints VINEETA

```

#### 5.2 lowercased

```swift
var name = "Vineeta"
print(name.lowercased())
//prints vineeta

```

## 6\. Finding Substrings

- Any String instance can be bridged to NSString using the type-cast operator (as), and any String instance that originates in Objective-C may use an NSString instance as its storage.
- `import Foundation` framework to your code to use NSString instances.

#### 6.1 hasSuffix

```swift
import Foundation
var str = "My name is Vineeta"
if str.hasSuffix("Vineeta"){
	print("true")
}else{
    print("false")
}
//prints true

```

#### 6.2 hasPrefix

```swift
import Foundation
var str = "My name is Vineeta"
if str.hasPrefix("My"){
	print("true")
}else{
	print("false")
}
// prints true 

```

## 7\. Finding Characters

#### 7.1 contains

- Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

```swift
let cast = ["Vivek", "vineet", "vineeta", "akshay"]
print(cast.contains("vineet"))
//prints true 
print(cast.contains("James"))
//prints false

```

#### 7.2 contains(where:)

- Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

```swift
let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
print(hasBigPurchase)
//prints true

```

#### 7.3 first(where:)

- Returns the first element of the sequence that satisfies the given predicate.

```swift
let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
print("The first negative number is \(firstNegative).")
}
// prints "The first negative number is -2."

```

#### 7.4 index(of:)

- Returns the first index where the specified value appears in the collection.

```swift
var students = ["Akshay", "vivek", "vineet", "vineeta"]
if let i = students.index(of: "Maxime") {
students[i] = "Max"
}
print(students)
//prints ["Akshay", "vivek", "vineet", "vineeta"]

```

#### 7.5 index(where:)

- Returns the first index in which an element of the collection satisfies the given predicate.

```swift
import Foundation
let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.index(where: { $0.hasPrefix("A") }) {
print("\(students[i]) starts with 'A'!")
}
// prints Abena starts with 'A'!

```

#### 7.6 max()

- Returns the maximum element in the sequence.

```swift
let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight ?? "nothing in there")
//prints 67.5

```

#### 7.7 max(by:)

- Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

```swift
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue ?? "nothing")
//prints (key: "Heliotrope", value: 296)

```

## 8\. Appending Strings and Characters

#### 8.1 append(\_:)

- Adds an element to the end of the collection.

```swift
var numbers = [1, 2, 3, 4, 5]
numbers.append(100)
print(numbers)
//prints [1, 2, 3, 4, 5, 100]

```

#### 8.2 append(\_:)

- Appends the given string to this string.

```swift
var name = "rachel"
name.append("ross")
print(name)
//prints rachelross

```

## 9\. Inserting Characters

#### 9.1 insert(\_:at:)

- Inserts a new character at the specified position.

```swift
var name = "rachel"
name.insert("a", at:name.startIndex)
print(name)
//prints arachelross

```

#### 9.2 insert(\_:at:)

- Inserts a new element into the collection at the specified position.

```swift
numbersArray.insert(100, at: 3)
numbersArray.insert(200, at: numbersArray.endIndex)
print(numbersArray)
//prints [1, 2, 100, 3, 4, 5, 200]

```

## 10\. Removing Substrings

#### 10.1 remove(at:)

- Removes and returns the character at the specified position.

```swift
var nonempty = "non-empty"
if let i = nonempty.characters.index(of: "-") {
    nonempty.remove(at: i)
}
print(nonempty)
//prints nonempty

```

#### 10.2 remove(at:)

- Removes and returns the element at the specified position.

```swift
var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
let removed = measurements.remove(at: 2)
print(measurements)
// Prints "[1.2, 1.5, 1.2, 1.6]"

```

#### 10.3 removeAll(keepingCapacity:)

- Replaces this string with the empty string.

```swift
var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
let removeAll = measurements.removeAll()
print(measurements)
//prints []

```

#### 10.4 removeFirst()

- Removes and returns the first element of the collection.

```swift
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst()
print(bugs)
// Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"

```

#### 10.5 removeFirst(\_:)

- Removes the specified number of elements from the beginning of the collection.

```swift
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst(3)
print(bugs)
// Prints "["Damselfly", "Earwig"]"

```

#### 10.6 removeLast()

- Removes and returns the last element of the collection.

```swift
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeLast()
print(bugs)
//prints ["Aphid", "Bumblebee", "Cicada", "Damselfly"]

```

#### 10.7 removeLast(\_:)

- Removes the specified number of elements from the end of the collection.

```swift
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeLast(2)
print(bugs)
//prints ["Aphid", "Bumblebee"]

```

#### 10.8 removeSubrange(\_:)

- Removes the elements in the specified subrange from the collection.

```swift
var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
measurements.removeSubrange(1..<4)
print(measurements)
//prints [1.2, 1.6]

```

#### 10.9 removeSubrange(\_:)

- Removes the elements in the specified subrange from the collection.

```swift
var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
measurements.removeSubrange(1..<4)
print(measurements)
// Prints "[1.2, 1.5]"

```

#### 10.10 filter(\_:)

- Returns a new collection of the same type containing, in order, the elements of the original collection that satisfy the given predicate.

```swift
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

```

## 11\. Getting Characters and Bytes

#### 11.1 subscript(\_:)

- Accesses the character at the given position.

```swift
let greeting = "Hello, friend!"
if let i = greeting.characters.index(where: { $0 >= "A" && $0 <= "Z" }) {
    print("First capital letter: \(greeting[i])")
}
//prints First capital letter: H

```

#### 11.2 first

- The first element of the collection.

```swift
let numbersArr = [10, 20, 30, 40, 50]
if let firstNumber = numbersArr.first {
    print(firstNumber)
}
//prints 10

```

#### 11.3 last

- The last element of the collection.

```swift
let numbersArr = [10, 20, 30, 40, 50]
if let firstNumber = numbersArr.last {
    print(firstNumber)
}
//prints 50

```

## 12\. Related String Types

#### 12.1 Substring

- A slice of a string.

```swift
let greeting = "Hi there! It's nice to meet you! 👋"
let endOfSentence = greeting.index(of: "!")!
let firstSentence = greeting[...endOfSentence]
print(firstSentence)
// firstSentence == "Hi there!"

```

#### 12.2 Converting a Substring to a String

- This example defines a rawData string with some unstructured data, and then uses the string’s prefix(while:) method to create a substring of the numeric prefix.

```swift
let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
print(numericPrefix)
//prints 126

```

## 13\. Describing a String

#### 13.1 description

```swift
let rawInput = "126 a.b 22219 zzzzzz"
print(rawInput.description)
// prints 126 a.b 22219 zzzzzz

```

#### 13.2 debugDescription

- A representation of the string that is suitable for debugging.

```swift
let rawInput = "126 a.b 22219 zzzzzz"
print(rawInput.debugDescription)
// prints "126 a.b 22219 zzzzzz"

```

#### 13.3 customMirror

- A mirror that reflects the String instance.

```swift
let rawInput = "126 a.b 22219 zzzzzz"
print(rawInput.customMirror)
// prints Mirror for String

```

#### 13.4 customPlaygroundQuickLook

```swift
let rawInput = "126 a.b 22219 zzzzzz"
print(rawInput.customPlaygroundQuickLook)
// prints text("126 a.b 22219 zzzzzz")

```

#### 13.5 hashValue

- The string’s hash value.

```swift
let rawInput = "126 a.b 22219 zzzzzz"
print(rawInput.hashValue)
// prints 9200157961725904825

```

## 14\. Creating a Range Expression

#### 14.1 ..<(\_:)

- Returns a partial range up to, but not including, its upper bound.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[..<3])
//prints [10, 20, 30]

```

#### 14.2 ...(\_:)

- Returns a partial range extending upward from a lower bound.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[3...])
//prints [40, 50, 60, 70]

```

#### 14.3 ...(\_:)

- Returns a partial range up to, and including, its upper bound.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[...3])
//prints [10, 20, 30, 40]

```

## 15\. Manipulating Indices

#### 15.1 startIndex

- The position of the first character in a nonempty string.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers.startIndex)
//prints 0

```

#### 15.2 endIndex

- A string’s “past the end” position—that is, the position one greater than the last valid subscript argument.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers.endIndex)
//prints 7

```

#### 15.3 index(after:)

- Returns the position immediately after the given index.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers.index(after: 3))
//prints 4

```

#### 15.4 index(\_:offsetBy:)

- Returns an index that is the specified distance from the given index.

```swift
let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// prints t

```

#### 15.5 index(\_:offsetBy:limitedBy:)

- Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

```swift
let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// prints "t"

```

#### 15.6 index(before:)

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers.index(before: 3))
//prints 2

```

#### 15.7 distance(from:to:)

- Returns the distance between two indices.

```swift
let numbers = [10, 20, 30, 40, 50, 60, 70]
let numDistance = numbers.distance(from: 0, to: 3)
print(numDistance)
//prints 3

```

## 16\. Iterating over a String's Characters

#### 16.1 forEach(\_:)

- Calls the given closure on each element in the sequence in the same order as a for-in loop.

```swift
let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// prints "one"
// prints "two"
// prints "three"

numberWords.forEach { word in
    print(word)
}
// prints "one"
// prints "two"
// prints "three"

```

#### 16.2 enumerated()

- Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

```swift
for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}
//prints 0: 'S'
//prints 1: 'w'
//prints 2: 'i'
//prints 3: 'f'
//prints 4: 't'

```

## 17\. Sorting a String's Characters

#### 17.1 sorted()

- Returns the elements of the sequence, sorted.

```swift
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
//prints ["Abena", "Akosua", "Kofi", "Kweku", "Peter"]

```

#### 17.2 sorted(by:)

- Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

```swift
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
//prints ["Peter", "Kweku", "Kofi", "Akosua", "Abena"]

```

#### 17.3 reversed()

- Returns a view presenting the elements of the collection in reverse order.

```swift
let word = "Backwards"
for char in word.reversed() {
    print(char, terminator: "")
}
//prints sdrawkcaB

```

## 18\. Working with String Views

#### 18.1 characters

- A view of the string’s contents as a collection of characters.

```swift
let word = "Backwards"
for char in word.characters{
	print(char)
}
//prints B
//a
//c
//k
//w
//a
//r
//d
//s

```

#### 18.2 init(\_:)

- Creates a string from the given character view

```swift
let poem = """
      'Twas brillig, and the slithy toves /
      Did gyre and gimbal in the wabe: /
      All mimsy were the borogoves /
      And the mome raths outgrabe.
      """
let excerpt = String(poem.characters.prefix(22)) + "..."
print(excerpt)
// Prints "'Twas brillig, and the..."

```

#### 18.3 withMutableCharacters(\_:)

- Applies the given closure to a mutable view of the string’s characters.

```swift
var str = "All this happened, more or less."
let afterSpace = str.withMutableCharacters { chars -> String.CharacterView in
    if let i = chars.index(of: " ") {
        let result = chars[chars.index(after: i)...]
        chars.removeSubrange(i...)
        return result
    }
    return String.CharacterView()
}

print(str)
// Prints "All"
print(String(afterSpace))
// Prints "this happened, more or less."

```

#### 18.4 unicodeScalars

- The string’s value represented as a collection of Unicode scalar values.

```swift
let word = "Backwards"
for char in word.unicodeScalars{
	print(char)
}
//prints B
// a
// c
// k
// w
// a
// r
// d
// s

```

#### 18.5 init(\_:)

- Creates a string corresponding to the given collection of Unicode scalars.

```swift
let picnicGuest = "Deserving porcupine"
if let i = picnicGuest.unicodeScalars.index(of: " ") {
    let adjective = String(picnicGuest.unicodeScalars[..<i])
    print(adjective)
}
//prints Deserving

```

#### 18.6 utf16

- A `UTF-16` encoding of self.

```swift
let picnicGuest = "Deserving porcupine"
print(picnicGuest.utf16.count)
//prints 19

```

#### 18.7 utf8

- A UTF-8 encoding of self.

```swift
let picnicGuest = "Deserving porcupine"
print(picnicGuest.utf8.count)
//prints 19

```

## 19\. Transforming a String's Characters

#### 19.1 map(\_:)

- Returns an array containing the results of mapping the given closure over the sequence’s elements.

```swift
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { print($0.lowercased()) }
//prints vivien
// marlon
// kim
// karl
let letterCounts = cast.map { print($0.count) }
//prints 6
// 6
// 3
// 4

```

#### 19.2 reduce(*:*:)

- Returns the result of combining the elements of the sequence using the given closure.

```swift
let numbers = [1, 2, 3, 4]
let numberSum = print(numbers.reduce(0, { x, y in
    x + y
}))
//prints 10

```

## 20\. Getting C Strings - utf8CString

- A contiguously stored null-terminated UTF-8 representation of the string.

```swift
let s = "Hello!"
let bytes = s.utf8CString
print(bytes)
// Prints "[72, 101, 108, 108, 111, 33, 0]"

```

**Next** \- [Operator Declarations by Example](https://developerinsider.co/operator-declarations-by-example-swift-programming-language/)

---

#### You can download the swift playground of all above examples from [Here](https://github.com/developerinsider/developer-insider-content/blob/master/POST/iOS/Swift/Playgrounds/String.playground.zip?raw=true&ref=developerinsider.co)

---