Splitting strings based on char number

string data = "0000062456" 

how to break this line into 5 parts so that I have:

 part[0] = "00"; part[1] = "00"; part[2] = "06"; part[3] = "24"; part[4] = "56"; 
+4
source share
4 answers

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

Of course, this can easily be converted to a function using an index that requires a substring:

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

If you really want a fantasy, you can also create an extension method.

 public static string getFromIndex(this string str, int arrIndex, int length) { return str.Substring(arrIndex * 2, length); } 
+4
source

If you are interested in LINQ solution:

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

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

+7
source

Edit: Invalid 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)); } 
+2
source

This is probably a bit redundant for the string, since Substring quite convenient, but the general question is how to split the collection into subgroups of a given size. The MoreLinq library has this function: Batch .
It can also take a lambda expression as a second parameter for direct conversion of subgroups, so the solution could be:

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

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

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

A good side effect of this approach is that it protects you from an extreme case - it will work as expected, even the length of your string will not be evenly divided along the length in substrings.

0
source

Source: https://habr.com/ru/post/1310724/


All Articles