开发者

string splitting based on char number

开发者 https://www.devze.com 2022-12-31 04:40 出处:网络
string data = \"0000062456\" how to split this string on 5 pieces so that I have: part[0] = \"00\"; part[1] = \"00\";
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] = "开发者_JAVA技巧56";


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.


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);
}


Edit: Wrong language

string str = "0000062456";
List<string> parts = new List<string>();
for (Int32 i = 0; i <= (str.Length / 2 - 1); i++) 
{
    parts.Add(str.Substring(i * 2, 2));
}


This probably a bit of an overkill for a string, since Substring is handy enough, but the general question is how to split a collection into subgroups of a given size. The library MoreLinq has such a function: Batch.
It can also take a lambda expression as the second parameter to convert the subgroups directly, so a solution can be:

IEnumerable<string> parts = str.Batch(2, String.Concat);

The above works for .Net 4.0. On 3.5 Concat need an array, so we can use ToArray or:

IEnumerable<string> parts = str.Batch(2, chars => new String(chars.ToArray()));

A nice side effect of this approach is that it protects you from edge case - it will work as expected even the length of your string doesn't divide evenly in the length on the sub-strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消