Ekli Ekli - 1 year ago 118
C# Question

C# . I need to find shortest words in every lines(from file)

I need to find shortest words in every lines with condition that these words shouldn't be shorter than "x"

For example this is the data:

It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum

and if i write for example x=5;

the result should be:




I know how to find just the longest words and that's it but how shortest with an condition don't:

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;

Answer Source

This will check each word, and will return the word that is greater than or equals x and shorter than the 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;


This is a function that takes a word and an array of letters, and returns the first letter that exists in the word.

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. 

You can call it like (GetLetter("Lorem", new char[] {'a', 'e', 'o'})). When you get that letter (i.e. o in "Lorem"), you can find all words that contain that letter as follow:

List<string> result = new List<string>();
foreach (var word in line)
    if (word.Contains(c)) result.Add(word);      // c is the letter
return result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download