Leon kong
Leon kong

Reputation: 149

Find the shortest string in an array of string

I need to provide a solution to find the shortest string in an array of string. I was thinking that it should be compare the length of each string in order to return.

This is where I was stuck

static void Main(string[] args)
{
    //find the shortest string in an array of string
    string[] names = new string[3]{
        "Tom", "and", "jerry"
    };

    foreach(string name in names){
        Console.Write(name + ", ");
    }

    Console.ReadKey();
}

Can anyone help me with the compare part and explain it

Upvotes: 6

Views: 17488

Answers (9)

Zoyeb Shaikh
Zoyeb Shaikh

Reputation: 334

            string[] countries = { "UK", "USA", "INDIA" };

            int? result = null;
            string nameOfCountry = string.Empty;
            foreach (var country in countries)
            {
                if (result == null || country.Length < result)
                {
                    nameOfCountry = country;
                    result = country.Length;
                }
            }
             

            Console.WriteLine(nameOfCountry);

Upvotes: 0

Oisin Carroll
Oisin Carroll

Reputation: 21

Nobody's provided the answer in a one-liner that runs in O(N) time. A better solution is to use .Aggregate:

var shortest = names.Aggregate((s, best) => s.Length < best.Length ? s : best)

Upvotes: 2

tbg10101
tbg10101

Reputation: 21

Write your own Linq, like this:

public static T1 Min<T1, T2>(this IEnumerable<T1> source, Func<T1, T2> selector) where T2 : IComparable<T2> {
    if (source == null) {
        throw new ArgumentNullException(nameof(source));
    }

    if (selector == null) {
        throw new ArgumentNullException(nameof(selector));
    }

    bool firstIteration = true;

    T2 minimum = default;
    T1 value = default;

    foreach (T1 v in source) {
        T2 current = selector.Invoke(v);

        if (current == null) {
            throw new NullReferenceException();
        }

        if (firstIteration || current.CompareTo(minimum) < 0) {
            minimum = current;
            value = v;
            firstIteration = false;
        }
    }

    return value;
}

These variable names are bad. It is up to you to improve them.

Upvotes: 0

manudicri
manudicri

Reputation: 173

Maybe you can do this:

string[] names = new string[3]{
 "Tom", "and", "jerry"
};
var query = from n in names select n.Length;
Console.WriteLine("Shortest name: " + names[Array.IndexOf(query.ToArray(), query.ToArray().Min())]);

I hope this can be useful to someone

Upvotes: 0

Mong Zhu
Mong Zhu

Reputation: 23732

this one will find the first shortest string without sorting the collection:

int minLength = names.Min(y=>y.Length); // this gets you the shortest length of all elements in names
string shortest = names.FirstOrDefault(x=>x.Length == minLength);

Explanation: it will check for that element which length is equal to the smallest length in the entire collection.

EDIT:

Can anyone help me with the compare part and explain it

To compare the length of a string use the Length property and the == operator. You can do this of course also in a loop as ChoockY did.

Upvotes: 15

Salah Akbari
Salah Akbari

Reputation: 39956

Use LINQ:

var shortestString = names.OrderBy(c => c.Length).FirstOrDefault();

Upvotes: 10

Anton&#237;n Lejsek
Anton&#237;n Lejsek

Reputation: 6103

You can use MaxBy for this. And please PLEASE do not sort the entire sequence just to find maximum. This is very wasteful, intentional wasting is the cancer that would kill performance of your software.

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222582

you can do this wiht linq,

var shortestName = names.OrderBy(name => name.Length).FirstOrDefault();

or

string shortestName = names.Aggregate((a1, a2) => a1.Length <a2.Length ? a1 : a2);

Upvotes: 4

ChoockY
ChoockY

Reputation: 94

You can use LINQ, as the others say. This is the easiest way to do the job, but i think, you should learn some algorithms. Finding the minimum/maximum value in an array belongs to programming basics.

Here can you read about it: http://www.stoimen.com/blog/2012/05/21/computer-algorithms-minimum-and-maximum/

The pure c# impementation looks like:

string[] names = new string[3]{
     "Tom", "and", "jerry"
};

string minValue = names[0];
foreach (string name in names)
{
     if (name.Length < minValue.Length)
     {
          minValue = name;
     }
}

Console.WriteLine(minValue);

Upvotes: 2

Related Questions