2

i have lists of phone numbers each phone number must have 10 numbers, i want simple code to add "," after every phone number to i can send it in SMS application.

i have it in this way :

0123456789

0123456789

0123456789

0123456789

0123456789

0123456789

i want the output look like this :

0123456789,0123456789,0123456789,0123456789,0123456789,0123456789

orig = "012345678901234567890123456789"
Dim res = Enumerable.Range(0,orig.Length\10).[Select](Function(i) orig.Substring(i*8,8))
Rabeea Qabaha
  • 378
  • 3
  • 8
  • 23

2 Answers2

4

So you have a single string which contains all numbers? Strange. However....

Dim orig = "012345678901234567890123456789"
Dim allNumbers As New List(Of String)
For i As Int32 = 0 To orig.Length - 1 Step 10
    Dim number As String
    If i + 10 >= orig.Length Then
        number = orig.Substring(i)
    Else
        number = orig.Substring(i, 10)
    End If
    allNumbers.Add(number)
Next

Now you can use String.Join:

Dim result = String.Join(",", allNumbers)  ' 0123456789,0123456789,0123456789

This is the most efficient approach and it is also readable. If you insist on a LINQ approach, here it is (method syntax ugly as always in VB.NET):

Dim numGroups = orig.
    Select(Function(chr, index) New With {.Char = chr, .Index = index}).
    GroupBy(Function(x) x.Index \ 10).
    Select(Function(g) String.Concat(g.Select(Function(x) x.Char)))
Dim result = String.Join(",", numGroups)

The trick is to group by x.Index \ 10 which is integer division in VB.NET, the decimal part is truncated, so it builds groups of ten.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

The String.join() function is probably the one you are looking for.

See the official documentation on MSDN website.

Antwane
  • 20,760
  • 7
  • 51
  • 84