Saturday, 9 February 2013

VB.NET split strings by length


VB.NET split strings by length

String methods are available to split strings by delimiters.  If user wants to split by length and last remaining portion of the string may may not be of the same length as user specified.

for ex: String str = "a ab abc abcd abcd abcdcd";

Split by 3    -> last string will be   "d " only(1char)


Here is  a method to Split a String by Length.


  Shared  Sub SplitStringsByLength(ByVal len As Integer)
          Console.WriteLine("SplitStringsByLength")
          Dim str As String =  "a ab abc abcd abcd abcdcd"

          While Not String.IsNullOrEmpty(str)

              Try
                  Console.WriteLine(str.Substring(0, len))
                  str = str.Remove(0, len)
              Catch ex As Exception
                  Dim break As Console.WriteLine("--"+str+"--")
              End Try
          End While
End Sub


call:  SplitStringsByLength(3);

OUTPUT

-a a-
-b a-
-bc -
-abc-
-d a-
-bcd-
- ab-
-cdc-
--d--



Note: String substr may through exception if string length is less than the length user specified,in that case get remaining portion of the string and break the loop.


Split a String by length using Regular Expression

User can split a string by using regular expressions.

suppose user's input:  str = "1111222233334444";

Get Sub Strings by length 3:

         Dim mc As MatchCollection =  Regex.Matches(str,"\w{3}")
          Dim i As Integer
          For  i = 0 To  mc.Count- 1  Step  i + 1
              Console.WriteLine("--"+mc(i).Value+"--")
          Next

output:

--111--
--122--
--223--
--333--
--444--

note: It won't return last digit i.e 4 in this case . str has 16 chars, it's returning only 15 chars,remaining string length is less than 3.

in This example Gets remaining Strings also

if Regular Expression is

\w{1,3}
output:
--111--
--122--
--223--
--333--
--444--
--4--

Example 2: Split Strings by Length using Regular Expressions.

Note: It includes chars & white spaces of length 1 to 3(max).

Dim str As String = "a ab abc abcd abcd abcdcd"
Dim mc As MatchCollection = Regex.Matches(str,"[\w\s]{1,3}")
Dim i As Integer
For  i = 0 To  mc.Count- 1  Step  i + 1
Console.WriteLine("--?" + mc(i).Value + "--"+i)
Next
 
output:
--?a a--0
--?b a--1
--?bc --2
--?abc--3
--?d a--4
--?bcd--5
--? ab--6
--?cdc--7
--?d--8
--?4--5
 

Tags:VB.NET split strings by length,How to Split a String by Length,How to split a string into smaller chunks,VB.NET splitting string in to array,Split a String by length using regular expressions, Split Strings by Regular Expressions, System.Text.RegularExpressions;,String.Substring