Swift program to find the longest word in a string


In Swift, a string is a sequence of characters. So a string can contain small and larger words. Hence using the following methods we can find the largest word in the string.

  • Using component() method

  • Using user-defined method

Example

Input String: "Rabbit run fast"

Output String: "Rabbit"

Here, the largest word among all the given words in the string is “Rabbit”.

Method 1: Using component() method

The components() method is used to create an array of substrings from the given string, where each substring is separated by the specified separator. So here we use the components(separatedBy:.whitespaces) method with .wihitespaces as a parameter to create an array of substrings in which the substrings are separated by a whitespace character. Then we compare the length of the array elements with each other to find the longest word.

Syntax

str.components(separatedBy:.whitespaces)

Here, the component() method is called on the str string and returns an array of substrings separated by whitespaces.

Algorithm

  • Step 1 − Create a function which takes an input string as a parameter and returns the longest word.

  • Step 2 − Inside the function, we create an array of substrings by dividing the string into substrings using the component() function. In which the substrings are separated by a whitespace character.

  • Step 3 − Create an empty string to store the result.

  • Step 4 − Run a for-in loop to iterate through each substring. And compare the length of each substring with the current substring.

  • Step 5 − If the current substring length is the largest length, then add this substring to the resultant string.

  • Step 6 − Return the resultant string.

  • Step 7 − Create a string.

  • Step 8 − Call the function and pass the string into it as a parameter

  • Step 9 − Display the output.

Example

import Foundation
import Glibc

// Function to find the longest word in the given string
func longestWord(str: String) -> String {
   let wordArray = str.components(separatedBy: .whitespacesAndNewlines)
   var longWord = ""
    
   for w in wordArray {
      if w.count > longWord.count {
         longWord = w
      }
   }
   
   return longWord
}

// Input string
let myString = "Swift support String"
let resWord = longestWord(str: myString)
print("Longest word in the \"\(myString)\" is:\(resWord)")

Output

Longest word in the "Swift support String" is: support

Method 1: Using User-Defined Function

We can find the longest word in a string using the user-defined function. Here we creat a function which takes the input string and returns the longest word present in the string.

Algorithm

  • Step 1 − Create a function which takes an input string as a parameter and returns the longest word.

  • Step 2 − Inside the function, we create two variables to store the current word while iterating each word and to keep track of the longest word.

  • Step 3 − Run a for-in loop to iterate through each substring.

  • Step 4 − Check if the current character is a whitespace or a newline because it represents the end of the word.

  • Step 5: − In that situation, we compare the length of the current word with the longest word.

  • Step 6 − Store the longest word in the variable

  • Step 7 − Again recheck to ensure that the word is the longest word.

  • Step 8 − Return the resultant word.

  • Step 9 − Create a string.

  • Step 10 − Call the function and pass the string into it as a parameter

  • Step 11 − Display the output.

Example

In the following Swift program, we will find the longest word in a string. So for that, we will define a function which takes a string as an input. This function iterates through each character of the string with the help of a for-in loop and checks if the character is whitespace or newline because it indicates the end of the word. In this situation, we compare the length of the currentWord and the longestWord and update the longestWord if necessary. Then we reset the currentWord to empty. If the character is not whitespace or newline, then we append it to the currentWord to generate the current word. After all the we again recheck to confirm that the resultant word is the longest word. Finally return the longest word.

import Foundation
import Glibc

func getLongestWord(str: String) -> String {
   var longestWord = ""
   var currentWord = ""
    
   for c in str {
      if c.isWhitespace || c.isNewline {
         if currentWord.count > longestWord.count {
            longestWord = currentWord
         }
         currentWord = ""
      } else {
         currentWord.append(c)
      }
   }
    
   if currentWord.count > longestWord.count {
      longestWord = currentWord
   }
    
   return longestWord
}

let myString = "Rohan lover Swift programming"
let resWord = getLongestWord(str:myString)
print("The longest word from the \" \(myString)\":\(resWord)")

Output

The longest word from the " Rohan lover Swift programming": programming

Conclusion

So this is how we can find the longest word in a string. Finding the longest word is useful for text analytics, data processing, game development, Unser input validation, language learning, etc. You can also use the longest word according to your need. Here both methods return the accurate results.

Updated on: 15-Jun-2023

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements