Joseph Jude

Technology, Psychology, and Story Telling

swift Challenge 008: Check if a string is a pangram

Posted: Tags: code,swift

Challenge: Write a program to check if the string entered by the user is a pangrams. Pangrams are sentences constructed by using every letter of the alphabet at least once. Ex: 'The quick brown fox jumps over the lazy dog'

Logic:

  • one way is to iterate over the characters of the alphabet and check if it is present in the phrase
  • since swift provides set operations, we can subtract set of alphabet characters from set of phrase characters
  • result of subtraction should be a 0 length set (since all chars of alpha should be in phrase)

Code:


func isPangram(phrase: String) -> Bool {
  let alphabet = "abcdefghijklmnopqrstuvwxyz"
  let (alphabetSet, phraseSet) = (Set(alphabet.characters), Set(phrase.lowercaseString.characters))
  let resultSet = alphabetSet.subtract(phraseSet)
  return resultSet.count == 0 ? true : false
}

var phrase = readLine()!
print(isPangram(phrase))

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.



Like the post? Retweet it. Got comments? Reply.

Comments

comments powered by Disqus