Gerando toda a substring de um determinado comprimento usando rendimento
Oct 27 2020
Eu preciso gerar toda a substring de um determinado comprimento, de uma string.
Por exemplo, todas as substrings de comprimento 3 de "abcdefg" são:
abc
bcd
cde
def
efg
Para esta tarefa, escrevi esta função:
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;
}
que eu uso assim:
foreach(string s in AllSubstringsLength("abcdefg",3))
System.Console.WriteLine(s);
Gostaria de saber se é possível escrever a mesma função evitando a variável resulte usandoyield
Respostas
4 E.Shcherbo Oct 27 2020 at 10:18
Claro, isso é possível
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);
}
}
Você também pode evitar ifo loop, modificando um pouco a condição para i <= input.Length - length, assim, seu método se torna:
public static IEnumerable<string> AllSubstringsLength(string input, int length)
{
for (int i = 0; i <= input.Length - length; i++)
{
yield return input.Substring(i, length);
}
}
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
Christopher Nolan uma vez se arrependeu de ter lido o 'roteiro de Pulp Fiction' de Quentin Tarantino