0

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.