Extract number at end of string in C#

前端 未结 9 2402
無奈伤痛
無奈伤痛 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:44

    Use this regular expression:

    \d+$
    
    var result = Regex.Match(input, @"\d+$").Value;
    

    or using Stack, probably more efficient:

    var stack = new Stack();
    
    for (var i = input.Length - 1; i >= 0; i--)
    {
        if (!char.IsNumber(input[i]))
        {
            break;
        }
    
        stack.Push(input[i]);
    }
    
    var result = new string(stack.ToArray());
    

提交回复
热议问题