Thursday 15 April 2010

c# - Finding the largest integer in a string of digits -


I have numbers that I have received as user input. How do I enter the maximum number?

For example, if the user entered 1236 9 85 , then the maximum number is 9 .

There is a way to do this, taking advantage of the fact that string Also IEnumerable & lt; Char & gt; . where section will take care of any non-numeric characters which were entered (because you are working with user input after all):

  Var input = "123456789"; Var max = input.Where (char.IsDigit). Select (x = & gt; int.Parse (x)). Maximum ();   

will be of the maximum type int . If you do not care about type conversion, you can terminate the Select statement.

No comments:

Post a Comment