Strings in Swift
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!"""
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
print
.
Swift Program
let str = "Hello, world!"
print(str)
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- 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
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in Swift are mutable if they are declared with
var
, so you can modify them using various methods. - 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!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
+
operator or the+=
operator. - Print the concatenated string.
Swift Program
let str1 = "Hello"
let str2 = " World!"
let str3 = str1 + str2 // Concatenating strings
print(str3)
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
contains
method to find a substring. - 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
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
count
property to get the length of the string. - 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