Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Longest Word in Swift #4516

Merged
merged 6 commits into from
Feb 18, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions archive/s/swift/longest-word.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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)
}
}