Click here to Skip to main content
16,018,057 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all I am a new bee here .

I need to split a string after x number of comma and move it to list.For example

String inputString='1,2,3,4,5,6,7,8,9,10,11,12,13,14,............'

If I split after five commas then result should be

VB.NET
Dim outputsting As New List(Of String)


outputsting[0] = 1,2,3,4,5
outputsting[1] = 6,7,8,9,10
outputsting[2]= 11,12,13,14,15 
and so on.


Is this possible in loop ?

Thanks in advance.
Posted
Updated 23-Nov-15 0:42am
v4

Use string.Split to break it into parts.
Then use Linq methods to extract the chunks:
VB.NET
Dim input As String = "1,2,3,4,5,6,7,8,9,10,11,12,13,14"
Dim parts As String() = input.Split(","C)
Dim first5 As String() = parts.ToList().GetRange(0, 5).ToArray()
Dim second5 As String() = parts.ToList().GetRange(5, 5).ToArray()
 
Share this answer
 
Comments
Member 12160400 23-Nov-15 5:34am    
I have thousands of records and need to push the values into list. While I iterate the list I will perform my logic. So, the each list item should contain 5 results while iterating

For Each s As String In outputsting
//Logic goes here
Next
Split the string to string array and then break the array in two part. Join the individual array to get the string.
VB
Dim inputString As [String] = "1,2,3,4,5,6,7,8,9,10,11,12,13,14"
Dim str As String() = inputString.Split(","C)
// First five elements
Dim str1 As String = String.Join(",", str, 0, 5) 
// Rest element
Dim str2 As String = String.Join(",", str, 5, str.Length - 5)  
 
Share this answer
 
v3
have a look at morelinq NuGet Package

VB
Dim input As String = "1,2,3,4,5,6,7,8,9,10,11,12,13,14"
For Each element As IEnumerable(Of String) In input.Split(","c).Batch(5)
    'your code here..
    Console.WriteLine(String.Join(", ", element))
Next


Quote:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11, 12, 13, 14
 
Share this answer
 
Using for loop:

VB
Dim outputstring As New List(Of String) 

Dim myArray() As String = inputString.Split(New Char(){","}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To CInt(myArray.Length/5)*5 Step 5
	Dim s As String = String.Join(",", myArray.Skip(i).Take(5))
	If Not s Is String.Empty Then outputstring.Add(s)
Next


Result:
1,2,3,4,5 
6,7,8,9,10 
11,12,13,14,15 
 
Share this answer
 
There's always the option of Regular Expressions:
VB
Imports System.Text.RegularExpressions

Dim outputstring As New List(Of String)
Dim inputString As String = "1,2,3,4,5,6,7,8,9,10,11,12,13,14"
For Each byFive As Match In Regex.Matches(inputString, "((?:\d+,){1,4}\d+),?")
    outputstring.Add(byFive.Groups(1).Value)
Next

The pattern can be enhanced to allow for whitespace (for example).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900