小编G. *_*ari的帖子

使用 yield 生成给定长度的所有子字符串

我需要生成一个字符串的给定长度的所有子字符串。

例如,“abcdefg”的所有长度为 3 的子串是:

abc
bcd
cde
def
efg
Run Code Online (Sandbox Code Playgroud)

为了这个任务,我写了这个函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用:

foreach(string s in AllSubstringsLength("abcdefg",3))
    System.Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以编写相同的函数来避免变量result并使用yield

c# string yield-return

5
推荐指数
1
解决办法
122
查看次数

为什么解构不能在左侧混合声明和表达式

我有以下代码:

public static (int a, int b) f12()
{
    return (1, 2);
}

public static void test()
{
    int a;
    (a, int b) = f12(); //here is the error
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,出现错误:

解构操作不能在左侧混合声明和表达式

我不明白为什么。有什么建议么?

c# tuples

3
推荐指数
1
解决办法
377
查看次数

标签 统计

c# ×2

string ×1

tuples ×1

yield-return ×1