我需要在每行中找到最短的单词,条件是这些单词不应短于“ x”
例如,这是数据:
它在1960年代开始流行,发布了包含Lorem Ipsum段落的Letraset工作表,最近又发布了包括Alres PageMaker在内的桌面发行软件,包括Lorem Ipsum的版本。
如果我写例如x = 5;
结果应该是:
洛雷姆
因此
洛雷姆
我知道如何找到最长的单词,仅此而已,但有条件的最短单词却找不到:
static string Longest(string line, char[] s, int x)
{
string[] parts =line.Split(s,StringSplitOptions.RemoveEmptyEntries);
string longg = "";
foreach (string word in parts)
if (word.Length >=longg.Length)
longg = word;
return longg;
}
这将检查每个单词,并返回大于或等于x
且小于的单词shortWord
。
static string Shortest(string line, char[] s, int x)
{
string[] parts =line.Split(s,StringSplitOptions.RemoveEmptyEntries);
string shortWord = "";
foreach (string word in parts)
if (word.Length >= x && (shortWord.Length == 0 || word.Length < shortWord.Length))
shortWord = word;
return shortWord;
}
更新
此函数接受一个单词和一个字母数组,然后返回单词中存在的第一个字母。
static char GetLetter(string word, char[] letters)
{
foreach(var c in word)
if (letters.Contains(c)) return c;
return '\0'; // return a default letter if no letters was found.
}
您可以像(GetLetter("Lorem", new char[] {'a', 'e', 'o'})
)这样称呼它。收到字母后(即o
中的"Lorem"
),您可以找到包含该字母的所有单词,如下所示:
List<string> result = new List<string>();
foreach (var word in line)
{
if (word.Contains(c)) result.Add(word); // c is the letter
}
return result;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句