Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all the substring of a given length using yield

Tags:

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

like image 871
G. Lari Avatar asked Oct 27 '20 10:10

G. Lari


1 Answers

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);
        }
    } 
like image 52
E. Shcherbo Avatar answered Sep 29 '22 11:09

E. Shcherbo