Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jweinst1/319e0cd35213e8eff0ab to your computer and use it in GitHub Desktop.
Save jweinst1/319e0cd35213e8eff0ab to your computer and use it in GitHub Desktop.
Functions that count words and letters in a string in swift.
//counts a specific letter in a string
func SpecificLetterCount(str:String, char:Character) ->Int {
var letters = Array(str); var count = 0
for letter in letters {
if letter == char {
count += 1
}
}
return count
}
// counts a specific word in a string
func SpecificWordCount(str:String, word:String) ->Int {
var words = str.componentsSeparatedByString(" "); var count = 0
for thing in words {
if thing == word {
count += 1
}
}
return count
}
func CountAllWords(str:String) ->[String: Int] {
var words = str.componentsSeparatedByString(" "); var wordcount = [String: Int]()
for word in words {
wordcount.updateValue(SpecificWordCount(str, word), forKey: word)
}
return wordcount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment