number of instances of the letter e in a given string in swift

main.swift
let inputString = "example string with letter 'e' in it"

var countOfE = 0
for character in inputString {
    if character == "e" {
        countOfE += 1
    }
}
print("Number of letter 'e' in the string: \(countOfE)")
219 chars
10 lines

Explanation:

  • The inputString is the string we want to count the instances of letter "e"
  • The countOfE variable is initialized as 0, which will be updated by the code later.
  • We use a for loop to iterate through each character in the inputString
  • If the character is "e", we increment the countOfE variable by 1.
  • After the loop ends, we print the result with the message "Number of letter 'e' in the string: X". X is the value of countOfE.

gistlibby LogSnag