Reputation: 167
I'm trying to find the position of the letters that make up a string. For example, I need to know the positions of the letter "c" in the word "character" for further calculation.
I tried
for letters in Array("character".characters) {
if "c".contains(String(letters)) {
if let i = Array("character".characters).index(of: letters) {
print(i)
}
} else { print("wrong letter") }
}
// Console:
0
wrong letter
wrong letter
wrong letter
wrong letter
0
wrong letter
wrong letter
wrong letter
All I get from the console are two zeros; it's only giving me the index of the first c in "character" but not the second c. The fact that it prints out "wrong letter" means the loop is running correctly; it even recognise the position of the second c, it's just not giving the correct index.
Upvotes: 0
Views: 2335
Reputation: 539795
Your code does not work as intended because
Array("character".characters).index(of: letters)
always finds the first occurrence of the letter in the string, e.g. when searching for "c" this will always return the index zero.
You can simplify the task by using enumerated()
,
which gives you the characters together with the corresponding index,
and makes all Array()
conversions and searching via index(of:)
unnecessary:
let word = "character"
let search = Character("c")
for (index, letter) in word.characters.enumerated() where letter == search {
print(index)
}
// 0 5
Or, if you want the indices as an array:
let indices = word.characters.enumerated()
.filter { $0.element == search }
.map { $0.offset }
print(indices) // [0, 5]
This can be further optimized to
let indices = word.characters.enumerated()
.flatMap { $0.element == search ? $0.offset : nil }
If the string is large then other methods might be better suited, see e.g. Find all indices of a search term in a string.
Upvotes: 1
Reputation: 969
You can do as
let test = "character"
let arr = Array(test.characters)
for i in 0..<arr.count {
if arr[i] == "c"{
print(i)
} else { print("wrong letter") }
}
output
// 0
//wrong letter
//wrong letter
//wrong letter
//wrong letter
//5
//wrong letter
//wrong letter
//wrong letter
Upvotes: 0