Generating all the substring of a given length using yield

北慕城南 提交于 2020-12-08 10:52:41

问题


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


回答1:


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);
        }
    } 


来源:https://stackoverflow.com/questions/64552253/generating-all-the-substring-of-a-given-length-using-yield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!