Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Created July 19, 2015 02:48
Show Gist options
  • Save jweinst1/9a10bc2365880d9f2f23 to your computer and use it in GitHub Desktop.
Save jweinst1/9a10bc2365880d9f2f23 to your computer and use it in GitHub Desktop.
Functions that allow you to check for the indexes at which a character appears in a string in Swift.
// returns a dictionary that holds the indexes for every character in a string
func StringIndexer(str:String) ->Dictionary<Int, Character> {
var strlist = Array(str); var strdict = [Int:Character](); var indexer = 0
for letter in strlist {
strdict.updateValue(letter, forKey: indexer)
indexer += 1
}
return strdict
}
// returns an array containing the indexes where a character appears in a string
func FindIndexCharacter(str:String, char:Character) ->Array<Int> {
let strdict = StringIndexer(str); var indexer = 0; var indexes = [Int]()
while indexer < count(str)-1 {
if strdict[indexer] == char {
indexes.append(indexer)
}
indexer += 1
}
return indexes
}
FindIndexCharacter("hello", "l")
// [2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment