Saturday, 9 February 2013

c# split strings by length

c# 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.


  static void SplitStringsByLength(int len)
      {
          Console.WriteLine("SplitStringsByLength");
          String str = "a ab abc abcd abcd abcdcd";
         
          while (!String.IsNullOrEmpty(str))
          {

              try
              {
                  Console.WriteLine(str.Substring(0, len));
                  str = str.Remove(0, len);
              }
              catch (Exception ex)
              {
                  Console.WriteLine("--"+str+"--"); break;
              }
          }
      }

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:

         MatchCollection mc= Regex.Matches(str, @"\w{3}");
          for(int i=0; i < mc.Count; i++)
          {
              Console.WriteLine("--"+mc[i].Value+"--");
        }

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

str="a ab abc abcd abcd abcdcd" ;

MatchCollection mc=Regex.Matches(str, @"[\w\s]{1,3}");
for (int i = 0; i < mc.Count; i++)
{
Console.WriteLine("--?" + mc[i].Value + "--"+i);
}

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:c# split strings by length,How to Split a String by Length,How to split a string into smaller chunks,C# splitting string in to array,Split a String by length using regular expressions, Split Strings by Regular Expressions, System.Text.RegularExpressions;,String.Substring