简体   繁体   中英

C# How to compare 2 numbers that were pulled from a string

I have to write a program that will intake a series of natural numbers separated by a comma like so [13,2,44,56,78,3,354] and pull a substring that has elements which are not smaller than the element before so for the example its [2,44,56,78]. If there are multiple such substrings to display the longer one. So far I have this.

using System;
using static System.Console;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {

    string s1 = ReadLine();

    string[] numbers = Regex.Split(s1, @"\D+");
    foreach (string value in numbers)
    {
        if (!string.IsNullOrEmpty(value))
        {
            int i = int.Parse(value);
            int highest = 
        }
    } WriteLine(s1);

    Console.ReadKey();
    }
}

Now I have to compare the numbers if the next one is smaller or bigger than the next and I am in a bind here. Any ideas?

Sorry I can't test this (or look up the correct calls) but hopefully you get the gist. You read each number and see if its >= than the previousNumber. If it is then you stash it in the list. Once there is a number that is less than the previous number you print the sequence out and clear the list.

List<int> sequence = new List<int>(10);
int previousNumber = -1;
int currentNumber = -1;
foreach (string value in numbers)
{
    if (!string.IsNullOrEmpty(value))
    {
        currentNumber = int.Parse(value);
        if (currentNumber >= previousNumber)
        {
            sequence[sequence.Length()] = currentNumber;
            previousNumber = currentNumber;
        }
        else
        {
            if (sequence.Length() > 1)
            { 
                // print sequence.
            }
            // Erase everything in the list.
        }
    }
}

If I understand you correctly, you need something like shown below:

string numbers = "13,2,44,56,78,3,354,1,2,3,4,5,4";
var values = numbers.Split(',').Select(a => int.Parse(a)).ToArray();

var maxStart = values.Length > 0 ? values[0] : 0;
var maxLength = values.Length > 0 ? 1 : 0;
int currentStart = 0;
int currentLength = 1;

for (int i=0; i<values.Length; i++)
{
    if (i + 1 < values.Length && values[i + 1] >= values[i])
        currentLength++;
    else
    {
        if (currentLength > maxLength)
        {
            maxLength = currentLength;
            maxStart = currentStart;
        }
        currentStart = i + 1;
        currentLength = 1;
    }
}
Console.WriteLine("Start={0}, Length={1}, Sequence={2}", maxStart, maxLength,
    string.Join(",", values.Skip(maxStart).Take(maxLength)));
//Start=7, Length=5, Sequence=1,2,3,4,5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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