我需要生成一个字符串的给定长度的所有子字符串。
例如,“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
我有以下代码:
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)
当我尝试编译它时,出现错误:
解构操作不能在左侧混合声明和表达式
我不明白为什么。有什么建议么?