Sum up numbers after splitting string and parsing to int - c#

I am learning c# and I encounter problem when attempting to sum the numbers from console input. User inserts numbers separated with commas. Then, they get splitted and at the end they should be parsed to int's for the future calculations as sum.
Here is what I've got:
int[] convertedLine;
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success = int.TryParse(splittedLine[0], out convertedLine);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
on 4th line I get error under convertedLine, that says 'cannot convert from out int[] to out int'.
I will appreciate help that will put me on the right track with my problem.
Thank you.
P
---------- edit ------------
Ok, so I've got this code now and it works. Is there a nicer way to do this parsing for all splitted elements of a string?
int[] convertedLine=new int[3];
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success1 = int.TryParse(splittedLine[0], out convertedLine[0]);
var success2 = int.TryParse(splittedLine[1], out convertedLine[1]);
var success3 = int.TryParse(splittedLine[2], out convertedLine[2]);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();

You need to initialize the elements of the convertedLine array and then specify the element you want to set to the value you pass to int.TryParse
Your .TryParse should look something like this:
var success = int.TryParse(splittedLine[0], out convertedLine[0]);
Note the [0] next to convertedLine that indicated the element in the int array you are setting
To initialize your convertedLine integer array simply do this line:
int[] convertedLine = new int[x];
Where x is the number of elements you want to have in your array. If you don't want to limit your user to a set amount of inputs you'll have to split on your split character and then initialize your integer array to however many values you found that the user input

The problem is here: int[] convertedLine; and then here: var success = int.TryParse(splittedLine[0], out convertedLine);
You are trying to parse to an array of integers a unique value of integers. Your code is assuming you have multiple integer as inputs

you are trying to convert the string to int in your case you pass an array of int and the function attempt to have an int a parameter.
try this one:
foreach(var i in splittedLine)
{
var success = int.TryParse(splittedLine[i], out convertedLine[i]);
}

The 'out' parameter from your int.TryParse is a single int. You're trying however to put that single int into an array of ints (which you've called 'convertedLine') without specifying where in the array that int should go.
One option then would be to declare your int array with a fixed size (eg)
int[5] convertedLine = new int[5];
which then allows for up to 5 integers. Then where you have
var success = int.TryParse(splittedLine[0], out convertedLine);
you should instead set a fixed value within the array, like this:
int.TryParse(splittedLine[0], out convertedLine[0]);
As an aside you also probably want to try and parse any other ints in the same way, eg:
int.TryParse(splittedLine[1], out convertedLine[1]);
int.TryParse(splittedLine[2], out convertedLine[2]);

Related

Displaying 3 smallest variables in an array on console?

I'm currently doing a beginner's coding exercise, and have run into a problem. The program I made takes 5 numbers, turns them into an array, and displays the three smallest numbers on the console. I have the input separated into an array, and created a new variable containing the three smallest values, but I'm not sure how to display each number in the array on the console.
I know that's a beginner question, but I've been coding less than a week. I tried searching StackOverflow and found a code to display each integer in a list, but am unsure what to change to display each value in an array.
bool isFive = new bool();
Console.WriteLine("Enter at least 5 numbers, separated by a comma.");
while (!isFive)
{
string text = Console.ReadLine();
string[] result = text.Split(',');
int[] resultInt = result.Select(s => int.Parse(s)).ToArray();
if (resultInt.Length < 5)
{
Console.WriteLine("Invalid list, retry.");
}
else
{
isFive = true;
var smallestThree = resultInt.OrderBy(x => x).Take(3);
????????????????
}
}
Almost there. All you need is string.Join:
Console.WriteLine(string.Join(", ", resultInt.OrderBy(x => x).Take(3)));
Also, instead of using int.Parse have a look at int.TryParse: Select parsed int, if string was parseable to int

Convert delimited record to seperate strings?

On my web form I have a token box where the user can select multiple answers and it compiles them using a ~ to separate them. I am trying to add up a score on this page and I need to split those values. I tried using this and it says cannot explicitly convert char to string. Lets say the fields answer is 3~4~5
How would I convert that to 3 4 5 in a manner that would allow me to perform a calculation.
string List1 = threeriskfactors.Text.ToString();
string[] Vals1 = List1.Split('~');
String name1 = List1[0];
String name2 = List1[1];
I have had no problems adding up single values from a drop down list but this is stumping me. For my other calculations my code looks like this:
int a1 = Convert.ToInt32(cancerisabnormalcells.SelectedValue.ToString());
int b1 = Convert.ToInt32(cancerissecondcause.SelectedValue.ToString());
int d1 = Convert.ToInt32(americancancersociety.SelectedValue.ToString());
int final1 = a1 + b1 + d1;
How do I split the token boxes value so I can add it to this calculation?
If you want the Sum of them then it is as simple as:
int final = List1.Split('~').Select(s => int.Parse(s)).Sum();
To Validate each value to see if it is parseable before parsing, you can use ForEach method of List:
List1.Split('~').ToList().ForEach(s => { int a =0; int.TryParse(s, out a); final +=a; });
IEnumerable<int> vals1 = list1.Select(e=> Convert.ToInt32(e));
int final1=0;
foreach(int val in vals1)
{
final1 = final1 + val;
}
This should do it.
var total = 0;
foreach (var item in list1.Split('~'))
total += Int32.Parse(item);
By the way, I'm not sure how you're concatenating the values to get the tilde-delimited string. But, it's worth noting that HTML forms will automatically create semicolon-delimited list of values from HTML form elements that share the same name.

Package 3 chars of Array into an integer C#

So, i have this array which contains a bunch of numbers. I want to always take 3 of those chars and make one integer out of them. I haven't found anything on this yet.
here is an example:
string number = "123456xyz";
The string is what I have, these integers are what I want
int goal1 = 123;
int goal2 = 456;
int goaln = xyz;
It should go through all the chars and always split them into groups of three. I think foreach() is going to help me, but im not quite sure how to do it.
Something like this:
var goals = new List<int>();
for (int i = 0; i + 2 < number.Length; i += 3)
{
goals.Add(int.Parse(number.Substring(i,3)));
}
This has no error checking but it shows the general outline. Foreach isn't a great option because it would go through the characters one at a time when you want to look at them three at a time.
var numbers = (from Match m in Regex.Matches(number, #"\d{3}")
select m.Value).ToList();
var goal1 = Convert.ToInt32(numbers[0]);
var goal2 = Convert.ToInt32(numbers[1]);
...

C# String Array to Double

Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.
First, here's my code so far:
//Prompts user to enter numbers
Console.Write("Enter a line of comma-seperated temperatures: ");
string temps = Console.ReadLine();
//Splits commas, seperating numbers into array
string[] numsInString = temps.Split(',');
int temps1 = numsInString.Length;
int[] temps2 = new int[temps1];
for (int i = 0; i < numsInString.Length; i++)
{
temps2[i] = int.Parse(numsInString[i]);
}
Console.WriteLine("Minimum temp: " + temps2.Min());
Console.WriteLine("Average temp: " + temps2.Average());
So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.
Thanks
You want to change the type of your array to double[] and then change your parsing to parse double instead of int:
double[] temps2 = new double[temps1];
for (int i = 0; i < numsInString.Length; i++)
{
temps2[i] = double.Parse(numsInString[i]);
}
As a bit of an aside, you can also use LINQ to express this more declaratively:
double[] temps2 = temps.Split(',')
.Select(double.Parse)
.ToArray();
As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double.
But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles.
Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);
Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach

Changing the order of a string based on an array of numbers in C#

Thanks for the help with my question about making an array of booleans into a string. The code is now working good. Now I have another problem. Maybe somebody would like to try. I think I could come up with a solution but if so I'm 99 percent sure that it would be not so simple as the answers I have seen from people here.
What I have is the string "ABD" from my question here. I also have an array of integers. For example [0] = 2, [1] = 3 and [2] = 1. I would like to find a way to apply this to my string to reorder the string so that the string changes to BDA.
Can anyone think of a simple way to do this?
If those integers are 1-based indices within the string (i.e. 2 = 2nd character), then you could do this:
string s = "ABD";
int[] oneBasedIndices = new [] { 2, 3, 1 };
string result = String.Join(String.Empty, oneBasedIndices.Select(i => s[i-1]));
NB: If you are using a version less than C# 4.0, you need to put a .ToArray() on the end of the select.
What this is doing is going through your int[] and with each int element picking the character in the string at that position (well -1, as the first index in an array is 0, but your example starts at 1).
Then, it has to do a String.Join() to turn that collection of characters back into a String.
As an aside, I'd recommend downloading LINQPad (no connection) - then you can just paste that code in there as a C# Program, and at any point type variable.Dump(); (e.g. result.Dump(); at the end) and see what the value is at that point.
First make a copy of the string. The copy will never change; it serves as your reference to what the values used to be.
Then loop through the original string one character at a time using a for loop. The counter in the for loop is the position of which character in the original string we are replacing next. The counter is also the index into the array to look up the position in the original string. Then replace the character at that position in the original string with the character from the copied string.
string orig = "ABD";
int[] oneBasedIndices = new [] { 2, 3, 1 };
string copy = orig;
for ( int i = 0; i < orig.Length; i++ )
{
orig[i] = copy[ oneBasedIndices[i] - 1 ];
}
There you have it. If the indices are zero based, remove the - 1.
Napkin code again...
string result = "ABD"; // from last question
var indecies = new []{ 1,2,0 };
string result2 = indecies.Aggregate(new StringBuilder(),
(sb, i)=>sb.Append(result[i]))
.ToString();
or a different version (in hopes of redeeming myself for -1)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < indecies.Length; i++)
{
sb.Append(result[i]); // make [i-1] if indecies are 1 based.
}
string result3 = sb.ToString();

Categories

Resources