Programming Fundamentals/Strings/Swift

From Wikiversity
Jump to navigation Jump to search

strings.swift[edit]

// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func find(text: String, substring: String) -> Int
{
    let range = text.range(of: substring)
    if range != nil
    {
        return text.distance(from: text.startIndex, to: range!.lowerBound)
    }
    else
    {
        return (-1)
    }
}

func substring(text: String, start: Int, end: Int) -> String
{
    let startIndex = text.index(text.startIndex, offsetBy: start)
    let endIndex = text.index(text.startIndex, offsetBy: end)
    return text[startIndex...endIndex]
}

func getName() -> String
{
    var name: String
    var index: Int

    repeat
    {
        print("Enter name (last, first):")
        name = readLine()!
        index = find(text: name, substring: ",")
    } while (index < 0)

    return name;
}

func getLast(name: String) -> String
{
    var last: String
    var index: Int

    index = find(text: name, substring: ",")
    if(index <= 0)
    {
        last = ""
    }
    else
    {
        last = substring(text: name, start: 0, end: index - 1)
    }
    
    return last;
}

func getFirst(name: String) -> String
{
    var first: String
    var index: Int

    index = find(text: name, substring: ",")
    if(index <= 0)
    {
        first = ""
    }
    else
    {
        first = substring(text: name, start: index + 1, end: name.characters.count - 1)
        first = first.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
    
    return first;
}

func displayName(first: String, last: String)
{
    print("Hello " + first + " " + last + "!")    
}

func main()
{
    let name = getName()
    let last = getLast(name: name)
    let first = getFirst(name: name)
    displayName(first: first, last: last)
}

main()

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own Swift compiler / interpreter / IDE.

See Also[edit]