The secondWith this, you would know which approach would be better for your case.
This is much better in logic and memory handling. The only missing part is a handling for splitMaxLength
where it might be <= 0
or >= stringToSplit.Length
.
I have modified your version to improve readability and code follow-up. and added some comments to explain some parts of the codechanges that I've made.
public static IEnumerable<string> SplitByLastIndexOf(string source, int blockSize, char delimiter)
{
// in case of invalid source
if (string.IsNullOrWhiteSpace(source)) yield break;
// in case of invalid block size.
if (blockSize <= 0 || blockSize >= source.Length)
{
blockSize = source.Length;
}
// reuse it rather than initializing it on each iteration
var removeSpace = 1;
// reuse it rather than initializing it on each iteration
var delimiterIndex = -1;
while (source.Length >= blockSize)
{
delimiterIndex = source.LastIndexOf(delimiter, blockSize);
if(delimiterIndex == -1)
{
// if a word is larger than blockSize we still split it
delimiterIndex = blockSize;
// taking care to not remove a non space character
removeSpace = 0;
}
yield return source[..delimiterIndex];
source = source[(delimiterIndex + removeSpace)..];
}
// return any remaining text.
if (source.Length > 0)
{
yield return source;
}
}