How to extract the beginning of a string (prefix) in Swift

1 Answer

0 votes
import Foundation

func extractPrefix(from str: String, lengthOfPrefix: Int) -> String {
    // Extract the prefix
    let prefix = String(str.prefix(lengthOfPrefix))
    
    return prefix
}

let str = "Swift Programming"
let lengthOfPrefix = 4 // Length of the prefix you want to extract

let prefix = extractPrefix(from: str, lengthOfPrefix: lengthOfPrefix)

print("Prefix: \(prefix)")




/*
run:

Prefix: Swif

*/

 



answered May 1, 2025 by avibootz
...