我有一些代码无法按预期工作。作为输出,我得到:
Concatenation.Concatenation+ConcatWord
我不知道如何让它按照我的意愿运作。它应该输出数组中最大的连接字及其字符数。输入可能是:
string[] words = {"five","fivetwo","fourfive","fourfivetwo","one","onefiveone","two","twofivefourone"}`
输出应为:
"fourfivetwo" with 11 characters
我认为这部分有问题,但我不确定。:
List<ConcatWord> concatWords = new List<ConcatWord>();
for (int i = 0; i < data.Length; i++)
{
ConcatWord concatWord = new ConcatWord(i, data[i]);
for (int j = 0; j < data.Length; j++)
{
if (i != j)
{
if (data[i].Contains(data[j]) && data[i].Length > data[j].Length)
{
concatWord.words.Add(data[j]);
}
}
}
}
答案 0 :(得分:1)
试试这个:
string[] words = { "five", "fivetwo", "fourfive", "fourfivetwo", "one", "onefiveone", "two", "twofivefourone" };
var allCombinations = words.SelectMany(w => words, (left, right) => left + right);
var combinedWords = words.Where(w => allCombinations.Contains(w));
string longestCombinedWord = combinedWords.OrderByDescending(w => w.Length).First();
Console.WriteLine(longestCombinedWord);
答案 1 :(得分:0)
以下是如何缩短
string[] data = { "five","fivetwo","fivetwo","fivetwo","fourfive","fourfivetwo","one","onefiveone","two","twofivefourone" };
string longestWord = data.OrderByDescending(words => words.Length)
.Distinct()
.First();
Console.WriteLine (longestWord);
答案 2 :(得分:0)
你可以将它分开。
class Program
{
static void Main()
{
var searchTerms = new List<string> {"one", "two", "three", "four", "five"};
var words = new List<string>
{
"five",
"fivetwo",
"fourfive",
"fourfivetwo",
"one",
"onefiveone",
"two",
"twofivefourone"
};
var wordsAndMatches = new Dictionary<string, int>()
{
{"five", 0}, {"fivetwo", 0}, {"fourfive", 0},
{ "fourfivetwo", 0}, {"one", 0}, {"onefiveone", 0},
{"two", 0}, {"twofivefourone", 0}
};
foreach (var word in words)
{
var numberOfMatches = GetNumberOfOccurances(word, searchTerms);
wordsAndMatches[word] = numberOfMatches;
}
foreach (var wordsAndMatch in wordsAndMatches)
{
var result = string.Format("{0} contains {1} number of matches.", wordsAndMatch.Key, wordsAndMatch.Value);
Console.WriteLine(result);
}
var highestNumberOfConcatenations = wordsAndMatches.Values.OrderByDescending(x => x).FirstOrDefault();
var wordWithHighestNumberOfMatches = wordsAndMatches.FirstOrDefault(x => x.Value == highestNumberOfConcatenations);
Console.WriteLine("{0} has the highest number of matches at {1} matches.", wordWithHighestNumberOfMatches.Key, wordWithHighestNumberOfMatches.Value);
}
private static int GetNumberOfOccurances(string word, IEnumerable<string> searchTerms)
{
return searchTerms.Count(word.Contains);
}
}