Basic String Operations


 Basic String Operations


  • Creating Strings: You can create strings using double quotes, like "Hello, world!". Swift also allows multi-line strings using triple quotes, which is useful for longer texts or code snippets.

  • Concatenation: To combine strings, you use the + operator. For example, "Hello" + " " + "World" results in "Hello World". You can also use string interpolation with \() to insert variables or expressions inside strings, such as "The score is \(score)".

  • Appending: You can add more text to an existing string using the append() method or the += operator. For example, myString.append(" Text") or myString += " Text" will add " Text" to myString.

  • Length: To find out how many characters are in a string, use the count property, like myString.count, which gives you the number of characters.

  • Accessing Characters: Swift strings are indexed by integer positions. To access a character at a specific position, use myString[index], where index is the position you’re interested in. For example, myString[myString.index(myString.startIndex, offsetBy: 2)] accesses the third character of myString.

  • Substrings: You can extract parts of a string using ranges. For example, myString[myString.startIndex..<myString.index(myString.startIndex, offsetBy: 5)] gets the first five characters.

  • Uppercase and Lowercase: Convert strings to all uppercase or lowercase using uppercased() and lowercased() methods, like "hello".uppercased() which gives "HELLO".

  • Trimming: Remove unwanted spaces from the beginning and end of a string with trimmingCharacters(in: .whitespaces), useful for cleaning up user input.

  • Checking Prefixes and Suffixes: Use hasPrefix(_:) and hasSuffix(_:) to check if a string starts or ends with a particular substring.


CODE EXAMPLE:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Creating Strings
        let singleLineString = "Hello, world!"
        let multiLineString = """
        This is a multi-line string
        that spans several lines.
        """
        
        // Concatenation
        let firstPart = "Hello"
        let secondPart = "World"
        let combinedString = firstPart + " " + secondPart
        
        // String Interpolation
        let score = 42
        let interpolatedString = "The score is \(score)"
        
        // Appending
        var myString = "Hello"
        myString.append(" World")
        myString += "!"
        
        // Length
        let length = myString.count
        
        // Accessing Characters
        let index = myString.index(myString.startIndex, offsetBy: 3)
        let thirdCharacter = myString[index]
        
        // Substrings
        let startIndex = myString.startIndex
        let endIndex = myString.index(startIndex, offsetBy: 5)
        let substring = myString[startIndex..<endIndex]
        
        // Uppercase and Lowercase
        let uppercaseString = myString.uppercased()
        let lowercaseString = myString.lowercased()
        
        // Trimming
        let rawString = "   Trim me   "
        let trimmedString = rawString.trimmingCharacters(in: .whitespaces)
        
        // Checking Prefixes and Suffixes
        let hasHelloPrefix = myString.hasPrefix("Hello")
        let hasWorldSuffix = myString.hasSuffix("World")
        
        // Printing results to console
        print("Single Line String: \(singleLineString)")
        print("Multi Line String: \(multiLineString)")
        print("Combined String: \(combinedString)")
        print("Interpolated String: \(interpolatedString)")
        print("Appended String: \(myString)")
        print("Length of String: \(length)")
        print("Third Character: \(thirdCharacter)")
        print("Substring: \(substring)")
        print("Uppercase String: \(uppercaseString)")
        print("Lowercase String: \(lowercaseString)")
        print("Trimmed String: \(trimmedString)")
        print("Has 'Hello' Prefix: \(hasHelloPrefix)")
        print("Has 'World' Suffix: \(hasWorldSuffix)")
    }
}

Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl