Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

.net - Extract number at end of string in C#

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 I have considered using a simple loop, LINQ and regex but I'm curious what approaches I'll get from the community. Obviously this isn't a hard problem to solve but could have allot of variance in the solutions.

So to be more specific, how would you create a function to return an arbitrarily long integer/long that is appended at the end of an arbitrarily long string?

CPR123 => 123
ABCDEF123456 => 123456
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this regular expression:

d+$

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

or using Stack, probably more efficient:

var stack = new Stack<char>();

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...