Search code examples
c#stringyield-return

Generating all the substring of a given length using yield


I need to generate all the substring of a given length, of a string.

For example all the substrings of length 3 of "abcdefg" are:

abc
bcd
cde
def
efg

For this task I wrote this function:

public static IEnumerable<string> AllSubstringsLength(string input, int length)
{
    List<string> result = new List<string>();
    for (int i = 0; i <= input.Length - length; i++)
    {
        result.Add(input.Substring(i, length));
    }
    return result;
}

that I use like this:

foreach(string s in AllSubstringsLength("abcdefg",3))
    System.Console.WriteLine(s);

I wonder if it is possible to write the same function avoiding the variable result and using yield


Solution

  • Sure, this is possible

        public static IEnumerable<string> AllSubstringsLength(string input, int length)
        {
            for (int i = 0; i < input.Length; i++)
            {
                if (i + length > input.Length) yield break;
                yield return input.Substring(i, length);
            }
        }
    

    You can also avoid if in the loop by modifying a bit the condition to i <= input.Length - length, thus your method becomes:

        public static IEnumerable<string> AllSubstringsLength(string input, int length)
        {
            for (int i = 0; i <= input.Length - length; i++)
            {
                yield return input.Substring(i, length);
            }
        }