Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string splitting based on char number

string data = "0000062456"

how to split this string on 5 pieces so that I have:

part[0] = "00";
part[1] = "00";
part[2] = "06";
part[3] = "24";
part[4] = "56";
like image 852
ilija veselica Avatar asked Dec 13 '22 21:12

ilija veselica


2 Answers

In case you are interested in a LINQ solution:

IEnumerable<string> result = Enumerable
    .Range(0, s.Length / 2)
    .Select(i => s.Substring(i * 2, 2));

Where you can replace 2 by any number you would like.

like image 157
Darin Dimitrov Avatar answered Dec 20 '22 08:12

Darin Dimitrov


Use Substring(int32, int32):

part[0] = myString.Substring(0,2);
part[1] = myString.Substring(2,2);
part[2] = myString.Substring(4,2);
part[3] = myString.Substring(6,2);
part[4] = myString.Substring(8,2);

This can of course be easily converted to a function, using the index you need the substring from:

string getFromIndex(int arrIndex, int length)
{
   return myString.Substring(arrIndex * 2, length);
}

If you really want to get fancy, you can create an extension method as well.

public static string getFromIndex(this string str, int arrIndex, int length)
{
   return str.Substring(arrIndex * 2, length);
}
like image 29
Oded Avatar answered Dec 20 '22 08:12

Oded