brandenwagner
brandenwagner

Reputation: 138

Find the position of a character in a string?

I need to find the position of a character in a string and to return an Int for further calculation.

let idx = cycleOrder.characters.indexOf(charInput)

This gives me the index, but how do I get this into an Int?

I tried:

intIdx = Int(idx)

but that doesn't work.

Upvotes: 0

Views: 681

Answers (1)

Narendra G
Narendra G

Reputation: 559

check this code for find index of given character as Int

 func findIndexOfCharacter(str :String, findElement: Character) -> Int? {
  for (index, value) in Array(str.characters).enumerate() {
   if value == findElement {
    return index
  }
}
return nil
}

// Console:
 findIndexOfCharacter("hello", findElement: "e") // 1

Upvotes: 1

Related Questions