Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String into smaller Strings by length variable

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" 
like image 292
BuddyJoe Avatar asked Jun 09 '10 18:06

BuddyJoe


People also ask

How do you split a string with a specific length in Python?

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.

How do I split a string into multiple strings?

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.

How do you split a string into segments?

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.


2 Answers

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); } 
like image 193
SLaks Avatar answered Sep 23 '22 21:09

SLaks


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.

like image 33
Hans Olsson Avatar answered Sep 21 '22 21:09

Hans Olsson