Created
July 20, 2015 20:14
-
-
Save jweinst1/319e0cd35213e8eff0ab to your computer and use it in GitHub Desktop.
Functions that count words and letters in a string in swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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