-1

I am solving counting valleys problem in interview preparation website. How can I traverse my string characters like Java in Swift:

Java:

for (int i=0; i<n; i++) {
 if (s.charAt(i) == 'A') { }
}

Swift:

for i in 0...n {
  if (s.???? == "A") {}
}

I looked Cannot find char at position and index of char of a string var in Swift 2 but all answers are writing extension to String.

How can I write like Java charAt() shortly in Swift?

Emre Değirmenci
  • 715
  • 6
  • 22
  • 1
    I do not understand anything from your answer – Emre Değirmenci Jan 24 '20 at 14:09
  • 1
    Does this answer your question? [Get nth character of a string in Swift programming language](https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language) – Toto Jan 24 '20 at 14:12
  • `print(countingHills(n: 8, s: "DDDUUUDD"))`is test case. I have to traverse s parameter with for loop like `s.charAt(i)` – Emre Değirmenci Jan 24 '20 at 14:16
  • @Scheff I guess it's a task [Counting Valleys](https://www.hackerrank.com/challenges/counting-valleys/problem) – Vadim Nikolaev Jan 24 '20 at 14:17
  • Yes, it is. But how can I write `charAt(i)` in swift? – Emre Değirmenci Jan 24 '20 at 14:19
  • 1
    @Dávid: Regarding your comment at Joakim's (now deleted) answer: `String` is a collection, but not an array of `Character`, so `Array(s)` is *not* useless. – Martin R Jan 24 '20 at 14:33
  • Dávid closed my question but I do not find the answer in https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language. Thank you Dávid! – Emre Değirmenci Jan 24 '20 at 14:41
  • Don't translate programs between languages word for word. Java and Swift are completely different languages. Good, clean, conventional code in one would be an absolute disaster in another. – Alexander Jan 24 '20 at 14:54

1 Answers1

2

Use the equivalent of an "enhanced" loop:

for c in s {
    if(c == 'A') ...
}
Thomas Timbul
  • 1,634
  • 6
  • 14