Swift String lowercased() Function



String lowercased() Function

The String structure in Swift provides a built-in function named lowercased(). This function is used to convert the given string into lowercase. For example, if we have a string "tuToriaLsPoInt", using the lowercased() function will convert all characters in the string to lowercase, resulting in "tutorialspoint".

Syntax

Following is the syntac of the lowercased function −

func lowercased()

Parameter

This function does not take any parameters.

Return Value

The function returns the string converted to lowercase.

Example 1

Swift program to convert the given string into a lowercase string:

import Foundation

// Declaring a string
var str = "LEARN SWIFT PROGRAMMING LanGuaGE"
print("Original String:", str)

// Converting the str into a lowercase string
// Using lowercased() function
let result = str.lowercased()

print("Lowercase String:", result)

Output

Original String: LEARN SWIFT PROGRAMMING LanGuaGE
Lowercase String: learn swift programming language

Example 2

Swift program to demonstrate the use of the lowercased() function:

import Foundation

// String
var str = "WelCoMe TO TUTORIALSPOINT"
print("Original String:", str)

// Converting the str into a lowercase string
// Using lowercased() function
print("Lowercase String:", str.lowercased())

Output

Original String: WelCoMe TO TUTORIALSPOINT
Lowercase String: welcome to tutorialspoint

Example 3

Swift program to convert the first n characters of a string into lowercase using the lowercased() function:

import Foundation
func lowercaseString(input: String, firstNChars: Int) -> String {

   // Ensure firstNChars is within the given string's length 
   let lastIndex = min(firstNChars, input.count)
   
   // Extracting the first n characters from the string
   let newSubString = input.prefix(lastIndex)
   
   // Convert the substring to lowercase
   let result = newSubString.lowercased()
   
   return result
}
var str = "MoHAN RUN ToWARDS MUKESH"
let X = 6

let resStr = lowercaseString(input: str, firstNChars: X)
print("Original String: \(str)")
print("Resultant String: \(resStr)")

Output

Original String: MoHAN RUN ToWARDS MUKESH
Resultant String: mohan 
swift_strings.htm
Advertisements