Home > Blockchain >  How to get highest value from string Split() c#
How to get highest value from string Split() c#

Time:04-22

so I want to print the oldest persons age (for example person writes: Patrick,50 Steven,25) the code will print: age of the oldest: age

Obviously this is an exercise I am not trying to hide it

Here is the base of the code:

while (true)
            {
                string input = Console.ReadLine();

                if (input == "")
                {
                    break;
                }

                string[] pieces = input.Split(",");

CodePudding user response:

You could do something like this:

    public static void Main(string[] args)
    {
        var oldestAge = 0;
        var oldestName = "";
    
        while (true)
        {
            string input = Console.ReadLine();

            if (input == "")
            {
                break;
            }

            string[] pieces = input.Split(",");


            for (var i = 0; i < pieces.Length; i  = 2)
            {
                var name = pieces[i]; 
                var age = int.Parse(pieces[i   1]);
                if (age > oldestAge)
                {
                    oldestAge = age;
                    oldestName = name;
                }
            }
         
        }
        Console.WriteLine($"{oldestName} {oldestAge}");
    }

We're storing the oldestAge and oldestName values, and we check against each person coming in whether they're older than the oldestAge -- setting oldestAge and oldestName if they are.

An example run of the program would look like:

Luke,25,Harry,32
Dan,33,Paul,75

Paul 75

CodePudding user response:

You're making a quite difficult exercise to start: I would advise you to start working with a list of ages and get the highest one, something like:

20, 50, 35, 15, 20
=> the result should be 50.

Once you have this right, you can start adding names to your list:

Alice, 20, Bjorn, 50, Charlie, 35, Dave, 15, Evelyn, 20
=> First thing to realise is that not all entries are numbers (the question "Is Charlie larger than 35?" makes no sense),
   so you need to find a way to check if the entry is a name or a number.
=> the result should be 50.

Now you'll be interested in the person who is actually 50 years old. You might do this by running through your list again, and taking the previous entry.

=> the result should be "Bjorn".

Then you might start wondering: in order to know the person with the highest age, I'm running through the list twice: once for knowing the highest age and once for knowing whose age this is, and you realise that you'd better keep the index of the highest age you're trying to find, so that you can use that index for retrieving the corresponding name without running through your list again.

Have fun

CodePudding user response:

First of all, you should create a class called Person, containing Name and Age as a property, Like

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; } = 0;

    public Person(string name, string ageStr)
    {
      this.Name = name;
      int.TryParse(ageStr, out this.Age);
    }
}

Once you split the string, create a list of Person class and add each person details,

List<Person> people = new List<Person>();
for(int i = 0; i < pieces.Length; i = i   2) //look at increment, jumping i by 2
{
    var person = new Person(pieces[i], pieces[i   1]);
    people.Add(person);
}

Now use Linq, OrderByDescending() & First() to get first highest record,

var eldestPerson = people.OrderByDescending(x => x.Age).First();

Now you can print, Name as well as Age of eldest person

Console.WriteLine($"Eldest Person Name: {eldestPerson.Name} Age: {eldestPerson.Age}");

CodePudding user response:

Assuming that the input string is in exactly the same format as you mentioned, you could try the following:

string[] pieces = input.Split(',');
var oldestAge = pieces.Select( (piece, i) =>
                                 i > 0 ? int.Parse(piece.Split(' ')[0]) : int.MinValue
                                 ).OrderByDescending(age => age).First();
Console.WriteLine(oldestAge);

CodePudding user response:

I needed some exercise in C# too. Here is my solution:

using System.Text.RegularExpressions;

string pattern = @"([0-9] )|([a-zA-Z] )";
string input = @"Patrick,50 Steven,25 Dirk,50";
RegexOptions options = RegexOptions.Multiline;

Dictionary<string, uint> persons = new Dictionary<string, uint>();

string name = "";
uint age = 0;
foreach (Match m in Regex.Matches(input, pattern, options))
{
    uint.TryParse(m.Value, out age);
    if (age == 0)
    {
        name = m.Value;
    }
    else
    {
        persons.Add(name, age);
    }
}

uint maxAge = persons.Values.Max();

foreach (var p in persons.Where(x => x.Value == maxAge))
{
    Console.WriteLine($"{p.Key} {p.Value}");
}

output:

Patrick 50
Dirk 50
  • This is, so far, the only solution which detects multiple persons having the maxAge ?

And, of course, regex101.com did help!

CodePudding user response:

You can use the Enumerable.Max from System.Linq to get the highest value from a list.

An example:

var ages = new string[4];
ages[0] = "10";
ages[1] = "45";
ages[2] = "55";
ages[3] = "100";

var highest = ages.ToList().Select(a => Convert.ToInt32(a)).Max();
Console.WriteLine(highest); //Prints out 100 to console
  •  Tags:  
  • c#
  • Related