Skip to content

Commit d099d55

Browse files
authored
Add Longest Word in Swift (#4516)
1 parent e27f07f commit d099d55

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

archive/s/swift/longest-word.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import Foundation
2+
3+
if (CommandLine.arguments.count < 2) {
4+
print("Usage: please provide a string")
5+
}
6+
else
7+
{
8+
var sentence = CommandLine.arguments[1]
9+
sentence = sentence.replacingOccurrences(of: "\n", with: "") //removing the break line if it contains any
10+
longestWord(input : sentence)
11+
}
12+
13+
func longestWord(input : String) -> Void
14+
{
15+
var longest = 0
16+
var testWord = ""
17+
18+
if(input == "")
19+
{
20+
print("Usage: please provide a string") //checking for empty string
21+
}
22+
23+
else
24+
{
25+
var substrings: [Substring] = [] //array to hold the array of the input strings
26+
substrings = input.split(separator: " ") //splitting the array by spaces
27+
28+
for word in substrings //iterate through the array
29+
{
30+
testWord = word.trimmingCharacters(in: CharacterSet(charactersIn: " "))
31+
if(testWord.count > longest)
32+
{
33+
longest = testWord.count //obtaining the longest count of words
34+
}
35+
}
36+
print(longest)
37+
}
38+
}

0 commit comments

Comments
 (0)