Swift Strings


Swift Strings

In this tutorial, we will learn about strings in Swift. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in Swift is a sequence of characters. Strings in Swift are represented by the String type, which is a collection of Character values. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in Swift using string literals enclosed in double quotes:

let str = "Hello, world!"

Multi-line strings can be created using triple double quotes:

let str2 = """Hello,
world!"""


Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using print.

Swift Program

let str = "Hello, world!"
print(str)

Output

Hello, world!


Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using the index method.

Swift Program

let str = "Hello"
print(str[str.startIndex]) // Accessing the first character
print(str[str.index(after: str.startIndex)]) // Accessing the second character

Output

H
e


Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Swift are mutable if they are declared with var, so you can modify them using various methods.
  3. Print the modified string.

Swift Program

var str = "Hello"
str.replaceSubrange(str.startIndex...str.startIndex, with: "J") // Modifying a character
str += " World!" // Appending new characters
print(str)

Output

Jello World!


String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator or the += operator.
  3. Print the concatenated string.

Swift Program

let str1 = "Hello"
let str2 = " World!"
let str3 = str1 + str2 // Concatenating strings
print(str3)

Output

Hello World!


Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the contains method to find a substring.
  3. Print the existence of the substring.

Swift Program

let str = "Hello, world!"
if str.contains("world") {
    print("Substring found")
} else {
    print("Substring not found")
}

Output

Substring found


String Length

  1. Create a string variable and initialize it with a value.
  2. Use the count property to get the length of the string.
  3. Print the length of the string.

Swift Program

let str = "Hello, world!"
print("Length of the string: \(str.count)")

Output

Length of the string: 13