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

3 Answers 3

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()

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

Comments

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)

2 Comments

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 stackoverflow.com/a/54877538/2303865
for index in str.indices { for idx in str[index...].indices { print(str[idx]) } }
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.