C# String Array to Double - c#

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

Related

Convert monetary string to array and total

I'm using c#, I have a string of cash entries I need to add together and get the total
arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";
While the below works, as soon as I add a decimal point or a string value to replace the numbers in the array with my generated numbers, the below crashes
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
I want to take these values from a form post:
arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";
And total them e.g. Total = 57.40
Anyone got any ideas, I'm struggling, thanks in advance.
The input is a string (not an array of string, but a single string).
You then have to take that string and split it into a list or array.
The values have decimals, so they cannot be dealt with as int. int is an integer; a whole number. You should deal with your data as a list of doubles.
When you convert from string to double, you should use tryparse, as you can more stringently enforce the conversion and check for exceptions as you go.
I've put a sample below, but note that I made it much more verbose than I normally would, just to (hopefully) more clearly show each of the steps.
If I was going to actually do this, I would use Linq more and combine multiple steps into single lines.
So something like this:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var inString = "24.90,10.60,1.90,20";
var stringValues = inString.Split(',');
List<double> doubleValues = new List<double>();
foreach(string v in stringValues){
double outNum;
double num = double.TryParse(v, out outNum)? outNum : 0;
doubleValues.Add(num);
}
Console.WriteLine(doubleValues.Sum(i => i)); // output = 57.4
}
}
Don't use , as a seperator. You can prefer ;.
For 10.000,00 formatting style
var sum = arrTotalSplitCosts.Text.Split(';').Select(decimal.Parse).Sum()
For 10,000.00 formatting style
var sum = arrTotalSplitCosts.Split(';').Select(a => decimal.Parse(a, CultureInfo.InvariantCulture)).Sum()

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

Sum up numbers after splitting string and parsing to int

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

iterate through string and count occurrences

This is the question:
Write a program that reads a string from the console and prints in alphabetical order all letters from the input string and how many times each one of them occurs in the string.
It seemed interesting and not too complicated at first, but I couldn't solve it.
public static void Letters()
{
string input;
Console.Write("Enter a string: ");
input = Console.ReadLine();
var chars = new List<char>();
//To populate characters with the letters of the input but without repetition
for(int index = 0; index < input.Length; index++)
{
if(!characters.Contains(input[index]))
characters.Add(input[index]);
}
//To increment the counter corresponding to the character index
int[] counter = new int[characters.Count];
//Now what ?!
}
My thinking is:
I create a collection to hold the letters of the input string, without any repetition.
Then I use an int array of the same size such that each int holds the number of times the corresponding letter has occurred in the input string.
I not only don't know how to implement this, but I have a feeling its not an ideal solution
to the problem. There's probably a query or a lambda expression that should make this easy
to implement and read.
Note: The question following this is of the same nature. The difference is that it asks
to replace the repeated letters with a single one "aaabbbccc" to "abc".
I will appreciate if the logic is described. I will try to implement it on my own,
just point me to the logic.
EDIT:
This my answer using a dictionary
public static void Letters()
{
string input;
Console.Write("Enter a string: ");
input = Console.ReadLine();
var dict = new Dictionary<char, int>();
for(int index = 0; index < input.Length; index++)
{
char theKey = input[index]; //just for clarity
if(!dict.ContainsKey(theKey))
dict.Add(theKey, 1);
else
dict[input[index]]++;
}
foreach(var key in dict.Keys)
{
Console.WriteLine("{0}\t{1}", key, dict[key]);
}
Dictionnary<String, int>
Key = string = letter IE a,b,c,d,e,f.....
Int is number of occurence
So start by doing this :
Dictionnary.add(a,0)
...
Dictionnary.add(z,0);
And then read the string and do this
Dictionnary[letterFound ] += 1;
There is a better way knowing what is the value in ASCi of each letter to init the dictionnary, but i don't think is mandatory for such exercice.
Good luck
var myString = "Hello";
var dict = new Dictionary<char, int>();
foreach(var c in myString)
{
if(!dict.ContainsKey(c))
dict.Add(c, 1);
else
dict[c]++;
}
var orderedDict = dict.OrderBy(x => x.Key);
foreach(var kvp in orderedDict)
{
Console.WriteLine("Letter: {0}, Times: {1}", kvp.Key, kvp.Value);
}
For simple and readable solution use LINQ, GroupBy and anonymous types
string input = Console.ReadLine();
var groupedLettersOrdered = input.GroupBy(x => x, (character, charCollection) =>
new {Character = character, Count = charCollection.Count()})
.OrderBy(x => x.Character);
foreach(var letterGroup in groupedLettersOrdered)
Console.WriteLine("Character {0}, Count: {1}", letterGroup.Character, letterGroup.Count);
However Dictionary<char, int> solution will be (should be) faster and better for large strings
Consider first that a character has a binary representation (sequence of 1s and 0s) just like a scalar value. Consider also that for a Latin alphabet like English, the alphabetical order and numerical order of their equivalents correspond.
So... you could do something like this:
define an array of ints of a size large enough to accommodate all possible character values (arbitrarily, we could make it 256 for a UTF-8 string).
iterate over each character in the string; for each character, convert the character to its integer equivalent, use that as an index into the array and increment the value at that index.
iterate over the array and for each non-zero element, print out the character equivalent of the array index and the contents of the element (character count)
string myString = "the quick brown fox jumps over the lazy dog";
byte[] bytes = Encoding.UTF8.GetBytes(myString);
int[] counts = new int[256];
foreach (var b in bytes)
{
counts[(int)b]++;
}
for (int i = 0; i < 256; i++)
{
if (counts[i] > 0)
{
Console.WriteLine("{0} - {1}", (char)(byte)i, counts[i]);
}
}
The above solution can easily be generalized to disregard case by performing GetBytes on myString.ToUpper(). To generalize to Unicode would be a little more work because you'd have to pair up the bytes in proper endian order.

Converting string to sum C#

So this time, I've got numbers entered in as a list, with a space delimiting each number. The code I've written now places the number in a row as it should, but fails out when I try and convert the string to Int32, killing the program and not giving me the sum. I don't understand errors well enough yet to be able to decipher exactly what the error is. How does a guy convert split string arrays into numbers to produce a sum?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Dynamic_Entry
{
class Program
{
static void Main()
{
Console.Write("Please provide a list of numbers, separated by spaces: ");
string list = Console.ReadLine();
string[] parts = list.Split(' ');
int sum = 0;
for (int i = 0; i < parts.Length ; i++)
{
Console.WriteLine("{0, 5}", parts[i]);
}
sum = Convert.ToInt32(list);
Console.WriteLine("-----");
Console.Write("{0, 5}", sum);
Console.ReadLine();
}
}
}
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine("{0, 5}", parts[i]);
sum += Convert.ToInt32(parts[i]);
}
Fixed.
You were trying to convert "1 2 3 4 5 55" to an int. You must convert "1", "2, "3"... to an int and add them to sum.
I'll add that if you want to Split the string, it would be better to do something like
string[] parts = list.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
In this way multiple spaces between numbers are removed (1 2 3 for example)
Andrei had posted a very simple example of use of LINQ...
int sum = parts.Sum(p => Convert.ToInt32(p));
This you would put OUTSIDE the for cycle. It converts to int and adds all the "parts". It means "for each part convert it to int and add it. Return the sum".
You can convert each string to an int and add them in a loop as #xanatos proposes, or you can use LINQ and Enumerable.Sum(), eg:
var sum=parts.Sum(part=>Convert.ToInt32(part));
or
var sum=parts.Select(part=>Convert.ToInt32(part))
.Sum();
The real benefit comes when you have more complex expressions, eg. when you need to filter values, extract properties etc.
For example, you could filter values greater than 3 like this:
var sum=parts.Select(part=>Convert.ToInt32(part))
.Where(num=>num>3)
.Sum();

Categories

Resources