简体   繁体   English

如何从字符串中获取最大值 Split() c#

[英]How to get highest value from string Split() c#

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所以我想打印最老的人的年龄(例如人写:Patrick,50 Steven,25)代码将打印:最老的年龄:年龄

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(",");

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.我们正在存储oldestAgeoldestName值,并检查每个进来的人是否比oldestAge ——如果是,则设置oldestAgeoldestName

An example run of the program would look like:该程序的示例运行如下所示:

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

Paul 75

First of all, you should create a class called Person , containing Name and Age as a property, Like首先,您应该创建一个名为Person的 class,其中包含NameAge作为属性,例如

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,拆分字符串后,创建人员列表Person并添加每个人的详细信息,

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,现在使用 Linq, OrderByDescending() & First()获得第一高记录,

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

Now you can print, Name as well as Age of eldest person现在您可以打印最年长者的NameAge

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

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.现在您会对实际 50 岁的人感兴趣。 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玩得开心

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
                                 ).Max();
Console.WriteLine(oldestAge);

You can use the Enumerable.Max from System.Linq to get the highest value from a list.您可以使用 System.Linq 中的Enumerable.Max从列表中获取最大值。

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

I needed some exercise in C# too.我也需要在 C# 锻炼一下。 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: output:

Patrick 50
Dirk 50
  • This is, so far, the only solution which detects multiple persons having the maxAge?到目前为止,这是唯一可以检测到多个具有 maxAge 的人的解决方案?

And, of course, regex101.com did help!当然, regex101.com确实有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM