0

To get characters from String using enumerated() method

let str = "Hello"

for (i,val) in str.enumerated() {
        print("\(i) -> \(val)")
}

now trying to enumerate same string inside for loop but from i position like

for (i,val) in str.enumerated() {
        print("\(i) -> \(val)")
        for (j,val2) in str.enumerated() {
            // val2 should be from i postion instead starting from zero
        }
}

How to enumerate and set j position should start from i?

Thanks

Harshal Wani
  • 2,249
  • 2
  • 26
  • 41

3 Answers3

2

You can use for in the str.indices and start inside loop based on outside loop.

let str = "abc"

for i in str.indices {
    for j in str[i...].indices {
        print(str[j])
    }
}

Output: a b c b c c


(Suggestion from @LeoDabus)

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
  • 1
    That's expected as enumerated() method returns an offset not an index. Note that every iteration you are unnecessarily offsetting the index from the startIndex. Btw you should extend StringProtocol or the collection itself to englobe substrings as well. Check this post https://stackoverflow.com/a/54877538/2303865 – Leo Dabus Sep 28 '19 at 10:24
  • `for index in str.indices { for idx in str[index...].indices { print(str[idx]) } }` – Leo Dabus Sep 29 '19 at 02:49
2

You can use dropFirst() to create a view in the string starting with a specific position:

for (i,val) in str.enumerated() {
    print("i: \(i) -> \(val)")
    for (j, val2) in str.dropFirst(i).enumerated() {
        print("j: \(i+j) -> \(val2)")
    }
}

You need to add i in the second loop if you want to get the index corresponding to the original string, otherwise j will hold the index in the view created by dropFirst()

Cristik
  • 30,989
  • 25
  • 91
  • 127
0

If I understood the problem statement correctly, the OP requires this -

Hello
ello
llo
lo
o

We can use the suffix method provided by Apple.

let str = "Hello"
var lengthOfString = str.count

for (i, val) in str.enumerated() {
    print(String(str.suffix(lengthOfString - i)))
}

We don't need the val in the for loop above, so we can rewrite the above for loop as below.

var str = "Hello"
var lengthOfString = str.count

for i in 0..<lengthOfString {
    print(String(str.suffix(lengthOfString - i)))
}

Both the above for loops will give the same desired output.

Dhruv Saraswat
  • 858
  • 9
  • 13