This is my method to split strings into parts by last index of character and by max length, the rationale for this method is because I have to send, in a payload via POST
, a list of strings that cannot have more than 40 characters each, suffice to say that I can't cut words in half otherwise it would be much easier.
public IEnumerable<string> SplitStringByLastIndexOfAndMaxLength(string stringToSplit, int splitMaxLength, char delimiter)
{
while (!string.IsNullOrEmpty(stringToSplit))
{
if (stringToSplit.Length <= splitMaxLength)
{
yield return stringToSplit;
break;
}
var splitIndex = stringToSplit.LastIndexOf(delimiter, splitMaxLength);
var removeSpace = 1;
if (splitIndex < 0)
{
// if a word is larger than splitMaxLength we still split it
splitIndex = splitMaxLength;
// taking care to not remove a non space character
removeSpace = 0;
}
var partialString = stringToSplit[..splitIndex];
stringToSplit = stringToSplit[(splitIndex + removeSpace)..];
yield return partialString;
}
}
Usage, example with 40 characters max and split by space:
var address = "...Are included in two of the substrings. " +
"If you want to exclude the characters, you can " +
"add the periods... ...Are included in of the substrings. " +
"If you want to exclude the period characters, you can " +
"add the period... Some more text";
var addresses = SplitStringByLastIndexOfAndMaxLength(address, 40, ' ');
foreach (var address in addresses)
{
Console.WriteLine(address + " -> " + address.Length);
}
Output:
...Are included in two of the -> 29
substrings. If you want to exclude the -> 38
characters, you can add the periods... -> 38
...Are included in of the substrings. If -> 40
you want to exclude the period -> 30
characters, you can add the period... -> 37
Some more text -> 14
Can you think of improvements to be made?
(This could be made into an extension method but for the time being it's enough.)
StringBuilder
orStringReader
and take advantage ofyield return
this would help decrease memory allocation. \$\endgroup\$