Extract number at end of string in C#

前端 未结 9 2333
無奈伤痛
無奈伤痛 2020-12-17 08:03

Probably over analysing this a little bit but how would stackoverflow suggest is the best way to return an integer that is contained at the end of a string.

Thus far

相关标签:
9条回答
  • 2020-12-17 08:58

    Obligatory LINQ one-liner

    var input = "ABCD1234";
    var result = string.Concat(input.ToArray().Reverse().TakeWhile(char.IsNumber).Reverse());
    
    0 讨论(0)
  • 2020-12-17 09:02

    Is it always in the format LettersNumbers?

    In that case, this would work:

    Regex _cellAddressRegex = new Regex(@"(?<Column>[a-z]+)(?<Row>[0-9]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    var rowm = Convert.ToInt32(parts.Groups["Row"]);
    
    0 讨论(0)
  • 2020-12-17 09:04

    A simple loop should probably beat any other solution in its simplicity and efficiency. And final returned string can be just copied once without usage of Stack, StringBuilder, string.Concat or other more complex string supporting functions.

    string GetNumberFromEnd(string text)
    {
        int i = text.Length - 1;
        while (i >= 0)
        {
            if (!char.IsNumber(text[i])) break;
            i--;
        }
        return text.Substring(i + 1);
    }
    

    Or it can be even returned back directly as int type:

    bool GetIntFromEnd(string text, out int number)
    {
        int i = text.Length - 1;
        while (i >= 0)
        {
            if (!char.IsNumber(text[i])) break;
            i--;
        }
        return int.TryParse(text.Substring(i + 1), out number);
    }
    
    0 讨论(0)
提交回复
热议问题