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.
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.
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!"""
print
.let str = "Hello, world!"
print(str)
Hello, world!
index
method.let str = "Hello"
print(str[str.startIndex]) // Accessing the first character
print(str[str.index(after: str.startIndex)]) // Accessing the second character
H e
var
, so you can modify them using various methods.var str = "Hello"
str.replaceSubrange(str.startIndex...str.startIndex, with: "J") // Modifying a character
str += " World!" // Appending new characters
print(str)
Jello World!
+
operator or the +=
operator.let str1 = "Hello"
let str2 = " World!"
let str3 = str1 + str2 // Concatenating strings
print(str3)
Hello World!
contains
method to find a substring.let str = "Hello, world!"
if str.contains("world") {
print("Substring found")
} else {
print("Substring not found")
}
Substring found
count
property to get the length of the string.let str = "Hello, world!"
print("Length of the string: \(str.count)")
Length of the string: 13