Converting string to sum C# - 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();

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

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

How to input in an integer array

How can I take input in an array in C#?
I have written a code it's not working right. For example, if I input 1, then it gives an output 49.
using System;
using System.Collections.Generic;
using System. Linq;
using System.Text;
using System.Threading.Tasks;
namespace Google
{
class Program
{
static void Main(string[] args)
{
int n;
int[] array=new int[26];
Console.Write("Enter number of cases : ");
n = Console.Read();
for (int i = 0; i < n; i++)
{
array[i] = Console.Read();
Console.WriteLine( array[i]);
}
Console.Read();
}
}
}
arr = Array.ConvertAll(Console.ReadLine().Trim().Split(' '),Convert.ToInt32);
Console.Read returns the character code, not the number you entered.
Use int.Parse(Console.ReadLine()) instead:
n = int.Parse(Console.ReadLine());
//...
array[i] = int.Parse(Console.ReadLine());
49 is correct. this number is coming for the ascii value of the character "1"
Source (http://www.asciitable.com/)
You need to include a parser for your int.
As Selman22 said:
array[i] = int.Parse(Console.ReadLine());
will work for you.
Most of the competitive programming take inline integer input as the input array.
In that case console input can do this way:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
int n;
n =Int32.Parse(Console.ReadLine());
int[] arr = new int[n];
string[] s = Console.ReadLine().Split(' ');
for (int i= 0;i< n;i++)
{
arr[i] = Int32.Parse(s[i]);
}
Console.WriteLine(n);
foreach (var item in arr)
{
Console.Write(item+" ");
}
}
}
}
Console.Read method gets the next character from input stream, and converts it to integer value which is the ASCII value of the char. You want Console.ReadLine instead:
array[i] = int.Parse(Console.ReadLine());
Use int.TryParse if you want to validate user's input.
Btw it can be done with Read method if you want to get just numbers from 0 to 9 (which probably you don't), but the code will look ugly:
array[i] = int.Parse(((char)Console.Read()).ToString());
One liner solution:
var array = Console.ReadLine().Split().Select(int.Parse).ToArray();
Explanation
the array will be an array of integers read from the console input in one line separated by space.
Example Input: "1 2 3 4 5".
You are reading a char, not a number, in your case it is returning the ASCII value of 1, which is 49. You should use proper parsing functions like Int32.Parse(Console.ReadLine()).
1 coming across as 49 should be your hint. 49 is the ASCII value for the character '1'.
So what's happening is that your Console.Read() call is returning a char which is being implicitly cast as an integer into your integer array.
You probably actually expect the user to type a number and hit enter. So you'd probably be better off using Console.ReadLine() and then using int.TryParse on the string you get from that.

Sum of digits of a number in C#?

I am trying to write a code that sums the digits of a number and it should work, but I can't find where I am doing it wrong, I have a working code in Python for this and I tried to do it the same way in C# but.. Here are the two codes
Python:
number = "12346546"
summ=0
for i in number:
summ+=int(i)
print summ
C#:
string num = "2342";
int sum = 0;
for (int i = 0; i < num.Length; i++)
{
int number = Convert.ToInt32(num[i]);
sum += number;
}
Console.WriteLine(sum);
Edit: I used the Debugger and I found that when I am converting the numbers they turn out to be completely different numbers, but if I convert the whole string then it is converting correctly... how to fix this?
num[i] is a char and Convert.ToInt32 will return the ASCII code of the char instead of the actual numerical value.Use:
int number = Convert.ToInt32(num[i].ToString());
Also change i < num.Length-1 to i < num.Length
Edit: To make it more clear here is an example:
int n1 = Convert.ToInt32('0'); // Uses Convert.ToInt32(char) result -> 48
int n2 = (int) '0'; // cast from char to int result -> 48
int n3 = Convert.ToInt32("0"); // Uses Convert.ToInt32(string) result -> 0
replace Convert.ToInt32(num[i])
by
Convert.ToInt32(num[i].ToString())
else, you will get an ascii value... (cause num[i] is a char)
see msdn
There is no null at the end of a C# string, so you don't have to worry about it, and thus do not require the "-1" in your loop. However, there is a much easier way:
string num = "2342";
int sum = num.ToCharArray().Select(i => int.Parse(i.ToString())).Sum();
This converts the string to a character array, converts them all to ints (returning an IEnumerable<int> in the process) and then returns the sum of them all.
Convert.ToInt32(num[i]); would give you the ASCII value for the character digit. For example for character 1 you will get 49.
Use char.GetNumericValue like:
for (int i = 0; i < num.Length; i++)
{
int number = (int) char.GetNumericValue((num[i]));
sum += number;
}
You also need to modify your loop to continue till Length, since you are using <.
If you want to use LINQ then you can do:
int sum = num.Select(r => (int)char.GetNumericValue(r)).Sum();
A one line solution using Linq:
string num = "2342";
int sum = num.Sum(c=> Convert.ToInt32(c.ToString()));
Here's a fiddle: https://dotnetfiddle.net/3jt7G6
You can combine a few things.
You can select a collection of chars from a string using Linq (Sum() is a Linq method).
You still need to convert those characters into numbers; you can do this by converting a character to a string and parsing that or you can use another built-in method.
var sum = num.Sum(i => Char.GetNumericValue(i));
char is, at its core, just a number. It just happens to be a number representing a character.
Here are some solutions that highlight this:
int sum = num.Sum(c => c) - '0' * num.Length;
// or
int sum = 0;
for (int i = 0; i < num.Length; i++)
{
sum += num[i] - '0';
}

Need help in Hashtable implementation

i'm quite a beginner in C# , i tried to write a program that extract words from an entered string, the user has to enter a minimum length for the word to filter the words output ... my code doesn't look good or intuitive, i used two arrays countStr to store words , countArr to store word length corresponding to each word .. but the problem is i need to use hashtables instead of those two arrays , because both of their sizes are depending on the string length that the user enter , i think that's not too safe for the memory or something ?
here's my humble code , again i'm trying to replace those two arrays with one hashtable , how can this be done ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int i = 0 ;
int j = 0;
string myString = "";
int counter = 0;
int detCounter = 0;
myString = Console.ReadLine();
string[] countStr = new string[myString.Length];
int[] countArr = new int[myString.Length];
Console.Write("Enter minimum word length:");
detCounter = int.Parse(Console.ReadLine());
for (i = 0; i < myString.Length; i++)
{
if (myString[i] != ' ')
{
counter++;
countStr[j] += myString[i];
}
else
{
countArr[j] = counter;
counter = 0;
j++;
}
}
if (i == myString.Length)
{
countArr[j] = counter;
}
for (i = 0; i < myString.Length ; i++)
{
if (detCounter <= countArr[i])
{
Console.WriteLine(countStr[i]);
}
}
Console.ReadLine();
}
}
}
You're not doing too badly for a first attempt but this could be a lot better.
First thing: use TryParse rather than Parse when parsing an integer input by a human. If the human types in "HELLO" instead of an integer, your program will crash if you use Parse; only use Parse when you know that it is an integer.
Next thing: consider using String.Split to split the string into an array of words, and then process the array of words.
Next thing: code like yours that has a whole lot of array mutations is hard to read and understand. Consider characterizing your problem as a query. What are you trying to ask? I'm not sure I completely understand your code but it sounds to me like you are trying to say "take this string of words separated by spaces. Take a minimum length. Give me all the words in that string which are more than the minimum length." Yes?
In that case, write the code that looks like that:
string sentence = whatever;
int minimum = whatever;
var words = sentence.Split(' ');
var longWords = from word in words
where word.Length >= minimum
select word;
foreach(var longWord in longWords)
Console.WriteLine(longWord);
And there you go. Notice how the code reads like what it is doing. Try to write code so that the code conveys the meaning of the code, not the mechanism of the code.
One word. Dictioary (or HashTable). Both are standard datatypes you can use
Use a Dictionary for this (in your case, you are looking for a Dictionary).
Your extracted string will be the key, the length of it the Value.
Dictionary<string, int> words = new Dictionary<string,int>();
//algorithm
words.Add(word, length);

Categories

Resources