-2

The code bellow splits a string into strings of seven characters each into an array. Can someone please explain how it works in detail?

Dim orig = "12344321678900987"
Dim res = Enumerable.Range(0,orig.Length\8).[Select](Function(i) orig.Substring(i*8,8))
spongebob
  • 8,370
  • 15
  • 50
  • 83

1 Answers1

0
Dim orig = "12344321678900987"
Dim res = Enumerable.Range(0,orig.Length\8).[Select](Function(i) orig.Substring(i*8,8))

This code uses a few neat language tricks to reduce the amount of code required for digesting the string into smaller segments. Starting from inside out, first there is a Lambda Expression:

Function(i) orig.Substring(i * 8, 8)

This is a fancy way of creating Subs or Functions 'inline.' It essentially equates to:

Function subStr(ByVal i As Integer) As String
    Return orig.Substring(i * 8, 8)
End Function

The next part uses the Enumerable class, and its Range method to generate a series of numbers to feed into the lambda.

Enumerable.Range(0, orig.Length \ 8)

This is a fancier way of writing:

For i As Integer = 0 To (orig.Length \ 8)
    'Do something with i
End For

.[Select] is a little bit of magic that takes the current i in the loop (or range), and allows working with it. In this example it's:

subStr(i)

So this neat, one-line job can also be written as:

Dim orig As String = "12344321678900987"
Dim res as String()
For i As Integer = 0 To (orig.Length \ 8)
    Array.Resize(res, res.Length + 1)
    res(res.Length - 1) = subStr(i)
End For

Function subStr(ByVal i As Integer) As String
    Return orig.Substring(i * 8, 8)
End Function
Justin Ryan
  • 1,409
  • 1
  • 12
  • 25
  • For other examples: http://stackoverflow.com/questions/7376987/how-to-split-a-string-into-a-fixed-length-string-array?rq=1 – Justin Ryan May 10 '15 at 21:07