C# max() from string array not always biggest number - c#

This is a question around how the compiler/language deals with this.
Take the following code:
Console.WriteLine("Enter some numbers separated by ",");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
var maxNumber = splitNumber.Max();
Console.WriteLine("highest is: " + maxNumber);
Entering a string such as "1,2,3,4,5" will output the 5 as the max number.
However, using "1,2,3,55,6" outputs 6. Whereas, "33,1,4,1" gives 4. Bizarrely, "33,1,2,3" gives 33.
I know there is a better/simpler/different way of doing this using a loop. I am totally missing something with how the compiler is treating these strings to determine the output. Can someone explain it? Or provide me a reference to look it up?

In string comparison, 6 > 55 returns True.
Do this instead, Split the string into an array using Split() Extension method and then use MAX() function which Returns the maximum value in a generic sequence available in LINQ
string x = "1,2,3,55,6";
var array = x.Split(',');
Console.WriteLine("highest is: " + array.Max(c => int.Parse(c)));
Output:
highest is: 55

The "max" string is the last string in lexicographical order, i.e. the order you would list them in a dictionary
You need to use e.g. int.Parse to convert your strings to a number type if you want the numeric maximum.

You need to compare the number as ints from a list or array.
var <int> Numbers = new List<int>();
while(String had not ended)
{
var splitNumber = (int) numbers.Split(',');
Numbers.Add(splitNumner);
}
var maxNumber = Numbers.Max();
Console.WriteLine("highest is: " + maxNumber);

You can do this, Convert the string array to an array of int using ConvertAll and then find the max
Console.WriteLine("Enter some numbers separated by ");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
int[] myInts = Array.ConvertAll(splitNumber, int.Parse);
var maxNumber = myInts.Max();
Console.WriteLine("highest is: " + maxNumber);

I tried compiling your code with same inputs. I have also getting the same output but i thing when u try to perform .Max() operation on a string array it is only comparing the first character of each entries in your second array.
If the input is 1,2,3,55,6 you are gonna get the output as 6 because when you compare all the numbers and there first digit 6 is the largest. But if you change the input to 1,2,3,75,6 now you are gonna get the output as 75 because 7 is the biggest first digit of all the numbers in the list.
string str = "1,2,3,75,6";
var splitNumber = str.Split(',');
var maxNumber = splitNumber.Max();
Like all the other answers u need to convert the string array into an integer array and then apply it.

Ans for how the compiler is treating these strings to determine the output?:
As these are strings, string equality gets checked for it.
The compiler takes each string value and compares it to one by one char. It deduces equality on the first occurrence of mismatch (e.g. in 55 vs 6, 5 is less than 6, hence 55 is less than 6)

You can use this :
Console.WriteLine("Enter a series of number separated by comma and I will tell you which one is the biggest, cool!");
var input = Console.ReadLine().Split(',');
Console.WriteLine("Biggest is :" + input.Max(c => int.Parse(c)));

You can also do this:
var splitNumber = numbers.Split(',').Select(c=>Convert.ToInt32(c)).Max();
Console.WriteLine("highest is: " + splitNumber);

change Var to Int64
Int64 maxNumber = Int64.Parse(splitNumber.Max());

Related

Substring issues - input string was not in a correct format

I'm randomly generating simple math equations and need to get the numbers from the string and convert them into integers so I can add them. However, when I run the program I receive the "input string was not in the correct format" error on the "int N1Q1" line.
Is there something I'm missing? Would there be a better way to extract and convert a number from a string?
Question1.Text = Convert.ToString(random.Next(1, 9) + " + " + random.Next(1, 9) + " = ");
string FirstQuestion = Convert.ToString(Question1.Text);
int N1Q1 = Convert.ToInt32(FirstQuestion.Substring(0,1));
int N2Q1 = Convert.ToInt32(FirstQuestion.Substring(5,1));
Here's a different way to go about it, you could make each random.Next() call into its own variable, then you wont have to do the conversions. Something like this:
int random1 = random.Next(1,9);
int random2 = random.Next(1,9);
Question1.Text = $"{random1} + {random2} = ";
You also don't need to convert Question1.Text to a string, because it is already a string. Also, using this method, you already have the random numbers captured as variables, then you wont have to convert them back into integers
Looks like you are off by one in your substring in N2Q1:
int N2Q1 = Convert.ToInt32(FirstQuestion.Substring(4, 1));
do not forget to declare at the first place the random as the following
Random random = new Random();
second, in N2Q1 you calculated wrong, it should be as the following:
int N2Q1 = Convert.ToInt32(FirstQuestion.Substring(4, 1));

Truncating a version number C#

If I have a version number that has 5 digits such as "1.0.420.50.0", how could I truncate this number (and other version numbers like "1.0.512.500.0") to only 4 digits? "1.0.420.50.0" --> "1.0.420.50"
I would prefer to use an array but any other methods work too!
Thanks for any advice in advance!
I haven't programmed in c# in a while so the syntax may be off. If the versioning can be more than six digits, you won't want a method that relies on removing the last digit. Instead just take the first four version numbers.
String version = "1.0.420.50.0";
String [] versionArray = version.Split(".");
var newVersion = string.Join(".", versionArray.Take(4));
If it's a string, you could do something like
ver = "1.2.3.4.5";
ver = ver.substring(0, ver.lastindexof(".");
this should give you all the way up to the last ".". This is not very robust if your version numbers get longer or shorter, but it would work for a 5 digit version number. This is also the basic idea you want if you have a string.
Get the index of the last period and then get the substring from index 0 to the index of the last period. EX:
string version = "1.0.420.50.0";
int lastPeriodIndex = version.LastIndexOf('.');
string reformattedVersion = version.Substring(0, lastPeriodIndex);
through using an array, if that's what you really want:
string version = "1.0.420.50";
var numbers = version.Split(new char[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
string reformattedVersion = numbers[0] + '.' + numbers[1] + '.' + numbers[2] + '.' + numbers[3];
but that's a much less elegant/quick solution.

How to read Two numbers in c# [duplicate]

This question already has answers here:
reading two integers in one line using C#
(12 answers)
Closed 8 years ago.
INPUT
67 89 (in single line)
I have to input two numbers from console , and store in two different integers variable .
HOw to do it.
This will read a line from the console, split the string, parse the integers, and output a list. You can then take each number from the list as needed.
Console.ReadLine().Split().Select(s => int.Parse(s)).ToList()
If there will always be two numbers you can do it as follows:
var integers = Console.ReadLine().Split().Select(s => int.Parse(s)).ToArray();
int first = integers[0];
int second = integers[1];
Areas for improvement:
You might want to use TryParse instead of Parse and output a friendly error message if the input does not parse
If you require exactly 2 numbers (no more, no less) you might want to check the length of integers and output a friendly error message if <> 2
TryParse() example as requested:
var numbers = new List<int>();
foreach (string s in Console.ReadLine().Split())
{
if (int.TryParse(s, out int number))
numbers.Add(number);
else
Console.WriteLine($"{s} is not an integer");
}
using System;
public class Program
{
static void Main(string[] args)
{
var numbers = Console.ReadLine();
var numberList = numbers.Split(' ');
var number1 = Convert.ToInt32(numberList[0]);
var number2 = Convert.ToInt32(numberList[1]);
Console.WriteLine(number1 + number2);
Console.ReadKey();
}
}
If you executing from other program the you need to read from the args
var result = Console.ReadLine().Split(new [] { ' '});
Something along those lines, top of my head.
See the documentation for Console.ReadLine() and String.Split()
Using Linq you can then project into an int array:
var result = Console.ReadLine()
.Split(new[] { ' ' }) //Explicit separator char(s)
.Select(i => int.Parse(i))
.ToArray();
And even a bit terser:
var result = Console.ReadLine()
.Split() //Assuming whitespace as separator
.Select(i => int.Parse(i))
.ToArray();
Result is now an array of ints.

How to select nominator and denominator from textbox in c#?

Example -
textbox.Text = "456/789";
var nominator = 456;
var denominator = 789
How could I code this in c# ?
Also, how could I make one number from elements of array. For example, {1,5,7,6} would become 1576.
And now, i have such bad idea, but i wont to know: if I have int number in nominator, I will do one method from my1.cs, if I have double number in nominator/denominator I will do method from another class called my2.cs . How I may code IF, if (number = int;bla bla bla...), if (number = double; bla bla bla...)
string[] input = textbox.Text.Split('/');
var nominator = input[0];
var denominator = input[1];
Assuming you will always have the input in that format.
String.Join will smash them back together for you. Just don't use a separator.
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
1)
var value = textbox.Text.Split('/');
var nominator = value[0];
var denominator = value[1];
2)
String.Join
For the numerator and denominator, you could use "substring" or "split" to split/select the numbers before and after the "/".
For the array, you could loop through it, and add each number to a string, then convert that string to an integer.
Hope this helps!
Something like:
1.
string[] numdenom = textbox.Text.Split('/');
var numerator = numdenom[0];
var denominator = numdenom[1];
2.
string[] digits = new string[] { "1","5","7","6" };
string number = string.Join(string.Empty, digits);
int numberValue = int.Parse(number); // or int.TryParse if you prefer
For the first question, splitting the nominator and denominator I would use simple substring methods:
textbox.Text.substring(0, textbox.text.indexof("\"); //denominator
textbox.text.substring(textbox.text.indexof("\") + 1); //numerator
For the second, I'd suggest using a foreach loop to loop through each item in the array and concatenate onto a string object. I say a string object so you don't end up adding the numbers together, getting 19 instead of 1576.
This should work for the numerator and denominator.
var parts = textbox.Text.Split('/');
var numerator = parts[0];
var denominator = parts[1];
As for combining the elements of an array, you'll need to convert and build up a string, then convert it back to a number.
var numbers = new[] {1, 5, 7, 6};
var builder = new StringBuilder();
for each (var i in numbers) {
builder.Append(i);
}
var result = int.Parse(builder.ToString());

Copy first few strings separated by a symbol in c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Categories