I'd like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer than the length. Looking for the most succinct (yet understandable) version.
Example:
string x = "AAABBBCC"; string[] arr = x.SplitByLength(3); // arr[0] -> "AAA"; // arr[1] -> "BBB"; // arr[2] -> "CC"
The string splitting can be done in two ways: Slicing the given string based on the length of split. Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list.
split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.
String split is used to break the string into chunks. Python provides an in-built method called split() for string splitting. We can access the split string by using list or Arrays. String split is commonly used to extract a specific value or text from the given string.
You need to use a loop:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) { for (int index = 0; index < str.Length; index += maxLength) { yield return str.Substring(index, Math.Min(maxLength, str.Length - index)); } }
Alternative:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) { int index = 0; while(true) { if (index + maxLength >= str.Length) { yield return str.Substring(index); yield break; } yield return str.Substring(index, maxLength); index += maxLength; } }
2nd alternative: (For those who can't stand while(true)
)
public static IEnumerable<string> SplitByLength(this string str, int maxLength) { int index = 0; while(index + maxLength < str.Length) { yield return str.Substring(index, maxLength); index += maxLength; } yield return str.Substring(index); }
Easy to understand version:
string x = "AAABBBCC"; List<string> a = new List<string>(); for (int i = 0; i < x.Length; i += 3) { if((i + 3) < x.Length) a.Add(x.Substring(i, 3)); else a.Add(x.Substring(i)); }
Though preferably the 3 should be a nice const.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With