Swift Program to Print even length words


To print even-length words we calculate the length of each word using the count property. Then we check if the length of the word is even or not. If yes, then we will print the word. Otherwise not.

Input

Str = “Learn Swift language”

Output

language

Here the given string has three words: “Learn", “Swift”, and “language”. But the output is “language” because its length is even that is 8.

Algorithm

  • Step 1 − Create a variable to store a string.

  • Step 2 − Split the string into words using the split() function.

  • Step 3 − Now run a for loop to iterate through each word.

  • Step 4 − Check if the length of the current word is even or not.

  • Step 5 − If the length of the word is even, then print that word. Otherwise not.

Example

import Foundation
import Glibc

let myString = "Welcome to the tutorialspoint. Here we learn Swift language"

print("String:", myString)

print("\nEven words from the string are:")
let letter = myString.split(separator: " ")

for L in letter {

   // Checking for even words
   if L.count % 2 == 0 {
      print(L)
   }
}

In the following Swift program, we will print even-length words. So first we create a string. Then we split the words of the string and then we run a for-in loop to iterate through each word of the given string and check if the current word length is even or not. If yes, then print that word in the output. This process will continue till the end of the string.

Output

String: Welcome to the tutorialspoint. Here we learn Swift language

Even words from the string are:
to
Here
we
language

Conclusion

So this is how we can print even-length words. Even numbers are those numbers that are completely divisible by 2. So here we only printed those words whose length is completely divisible by 2. Otherwise not.

Updated on: 09-May-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements