Longest Word in Swift

Published on 18 February 2025 (Updated: 18 February 2025)

Welcome to the Longest Word in Swift page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

import Foundation

if (CommandLine.arguments.count < 2) {
    print("Usage: please provide a string")
}
else 
{
    var sentence = CommandLine.arguments[1]   
    sentence = sentence.replacingOccurrences(of: "\n", with: "")    //removing the break line if it contains any
    longestWord(input : sentence)
}

func longestWord(input : String) -> Void
{
    var longest = 0
    var testWord = ""

    if(input == "")
    {
         print("Usage: please provide a string")    //checking for empty string
    }

    else 
    {
        var substrings: [Substring] = []    //array to hold the array of the input strings
        substrings = input.split(separator: " ")        //splitting the array by spaces
        
        for word in substrings    //iterate through the array
        {
            testWord = word.trimmingCharacters(in: CharacterSet(charactersIn: " "))
            if(testWord.count > longest)    
            {
                longest = testWord.count    //obtaining the longest count of words
            }
        }
        print(longest)
    }
}

Longest Word in Swift was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.