Вы можете создать метод, который строит фразу из заданных слов.Не очень эффективно (из-за Скип), но простую реализация:
private static IEnumerable<string> CreatePhrases(string[] words, int wordsCount)
{
for(int i = 0; i <= words.Length - wordsCount; i++)
yield return String.Join(" ", words.Skip(i).Take(wordsCount));
}
Отдыха прост - разделить вашу строку на слова, строить фразы, и получить вхождение каждой фразы в исходной строке:
var my_string = "In the end this is not the end";
var words = my_string.Split();
var result = from p in CreatePhrases(words, 2)
group p by p into g
select new { g.Key, Count = g.Count()};
Результата :
[
Key: "In the", Count: 1,
Key: "the end", Count: 2,
Key: "end this", Count: 1,
Key: "this is", Count: 1,
Key: "is not", Count: 1,
Key: "not the", Count: 1
]
Более эффективный способ создать последовательные группы элементов (работает с любым I Перечислимых):
public static IEnumerable<IEnumerable<T>> ToConsecutiveGroups<T>(
this IEnumerable<T> source, int size)
{
// You can check arguments here
Queue<T> bucket = new Queue<T>();
foreach(var item in source)
{
bucket.Enqueue(item);
if (bucket.Count == size)
{
yield return bucket.ToArray();
bucket.Dequeue();
}
}
}
И все расчеты можно было бы сделать в одной строке:
var my_string = "In the end this is not the end";
var result = my_string.Split()
.ToConsecutiveGroups(2)
.Select(words => String.Join(" ", words))
.GroupBy(p => p)
.Select(g => new { g.Key, Count = g.Count()});
Благодаря @dasblinkenlight, я пропустил это. – tribe84
@GrantWinney - нет, два вопроса похожи, но не то же самое. – tribe84
Как вы хотите разделить 'input'? –