Swift String Manipulation and Methods Example

1. Introduction

Strings in Swift are a sequence of characters and are used to store textual data. Swift provides a robust set of methods and properties to efficiently work with and manipulate strings.

2. Source Code Example

// 1. Declaring a string
let helloWorld = "Hello, world!"

// 2. Accessing characters
for character in helloWorld {
    print(character)
}

// 3. Concatenate strings
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print(fullName)

// 4. Interpolating strings
let age = 30
let introduction = "My name is \(firstName) and I am \(age) years old."
print(introduction)

// 5. Checking string emptiness
let emptyString = ""
if emptyString.isEmpty {
    print("The string is empty!")
}

// 6. Count characters in a string
let count = helloWorld.count
print("Number of characters in '\(helloWorld)' is \(count)")

// 7. String comparison
if firstName == "John" {
    print("\(firstName) is indeed John!")
}

// 8. String methods
let uppercaseString = firstName.uppercased()
print(uppercaseString)

let lowercaseString = "HELLO".lowercased()
print(lowercaseString)

Output:

H
e
l
l
o
,
 
w
o
r
l
d
!
John Doe
My name is John and I am 30 years old.
The string is empty!
Number of characters in 'Hello, world!' is 13
John is indeed John!
JOHN
hello

3. Step By Step Explanation

1. Declaring a String: Here, a constant string helloWorld is declared with the text "Hello, world!".

2. Accessing Characters: Strings in Swift are collections of characters. You can iterate over each character in a string using a for-in loop.

3. Concatenate Strings: Strings can be concatenated using the + operator. In the example, firstName and lastName are combined to produce fullName.

4. Interpolating Strings: String interpolation allows you to insert variables directly into a string using the \(variable) syntax.

5. Checking String Emptiness: The isEmpty property checks if the string is empty or not.

6. Counting Characters: The count property gives the number of characters in a string.

7. String Comparison: Strings can be compared for equality using the == operator.

8. String Methods: The uppercased() method converts a string to uppercase and the lowercased() method converts a string to lowercase.


Comments