How to effectively determine if a string starts with a number, and then get all subsequent numbers up to the first non-numeric character?

I have a requirement to sort rows containing such data:

var strings = new List<string>{"2009 Arrears","2008 Arrears","2008 Arrears Interest","2009 Arrears Interest"};

And they want the results to be ordered as follows:

  • "Debt of 2009"
  • "Interest for 2009
  • "Debt of 2008"
  • "Interest for 2008

It seems I need to create a function to see if a string starts with a number. If so, the function will receive all numbers up to the first character and sort the numerical result, and then sort the remaining characters in ascending order. I am having trouble trying to write a method that gets all the starting numbers in a string. What would be an effective way to do this?

+5
2
public int GetLeadingNumber(string input)
{
    char[] chars = input.ToCharArray();
    int lastValid = -1;

    for(int i = 0; i < chars.Length; i++)
    {
        if(Char.IsDigit(chars[i]))
        {
            lastValid = i;
        }
        else
        {
            break;
        }
    }

    if(lastValid >= 0)
    {
        return int.Parse(new string(chars, 0, lastValid + 1));
    }
    else
    {
        return -1;
    }
}

, , , , .

+7

:

var match = Regex.Match(text, @"^(\d+) (.*)$");

match.Groups[0].Value - , match.Groups[1].Value - ( "", " " ..)

LINQ ( , ):

string[] titles = new[] { "2008 Arrears", "2009 Arrears" };

var sortedTitles = 
    from title in titles
    let match = Regex.Match(title, @"^(\d+) (.*)$")
    orderby match.Groups[0].Value descending, match.Groups[1].Value
    select title;

listBox.ItemsSource = sortedTitles.ToArray();  // for example

; , - LINQ:

var sortedTitles =
    from title in titles
    let year = new string(title.TakeWhile(ch => char.IsDigit(ch)).ToArray())
    let remainder = title.Substring(year.Length).Trim()
    orderby year descending, remainder
    select title;
+7

All Articles