Getting the sum of all numbers in a character array - c#

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}

You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}

If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}

Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.

Related

How do I add integers to char[] array?

So I have to write a code that picks our random numbers from 1 to 100 and add them to a char[] array. But I'm having some difficulty doing so as I can only add the numbers to the array if I convert them to a char using (char) which changes the number. Can someone please help me?
Thanks,
public char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 101));
}
return l;
}
use ToChar() method of Convert class.
Convert.ToChar(new Random().Next(1, 101))
You cannot convert an integer larger then 9 into a char because it's considered as 2 chars, i.e. 10 will be considered as 1 and 0.
so I would recommend adding it to an array of strings
(except if your trying to get a random charcode which I dont think is the case, because why till 100?)
Personally, I'd use an int[] array instead
There shouldn't be any problem in storing ints up to 65535 in a char but you will have to cast it back to an int if you don't want it to be weird:
public static void Main()
{
var x = CreationListe(200);
foreach(var c in x)
Console.WriteLine((int)c); //need to cast to int!
}
public static char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 65536));
}
return l;
}
https://dotnetfiddle.net/z5yoBn
If you don't cast it back to int, then you'll get the char at that character index in the unicode table. If you've put 65 into a char, you'll get A when you print it, for example. This is because A is at position 65 in the table:
(ASCII table image posted for brevity's sake)

Collect the digits numbers in the decimal number C#

I want a method to remove the comma from the decimal number and then collect the digits. For example, if the user inputs 1,3 it will remove the comma and collect 1 and 3 together. I mean 1+3 =4. Can I use trim or replace?
public int AddSum(string x1)
{
string x = x1.Trim();
int n = Convert.ToInt32(x);
return n;
}
public int AddSum(string x1)
{
var digitFilter = new Regex(#"[^\d]");
return digitFilter.Replace(x1, "").Select(c => int.Parse(c)).Sum();
}
OR
public int AddSum(string x1)
{
return x1.Where(c => char.IsDigit(c)).Select(c => c - '0').Sum();
}
If you want to iterate over the characters in a string and compute the sum of digits contained therein, it's trivial:
public static int SumOfDigits( string s ) {
int n = 0;
foreach ( char c in s ) {
n += c >= '0' && c <= '9' // if the character is a decimal digit
? c - '0' // - convert to its numeric value
: 0 // - otherwise, default to zero
; // and add that to 'n'
}
return n;
}
It sounds like you want take a comma-separated string of numbers, add the numbers together, then return the result.
The first thing you have to do is use the Split() method on the input string. The Split() method takes an input string splits the string into an array of strings based on a character:
string[] numbers = x1.Split(',');
So now we have an array of strings called numbers that hold each number. The next thing you have to do is create an empty variable to hold the running total:
int total = 0;
The next thing is to create a loop that will iterate through the numbers array and each time, add the number to the running total. Remember that numbers is an array of strings and not numbers. so we must use the Parse() method of int to convert the string to a number:
foreach (string number in numbers)
{
total += int.Parse(number);
}
Finally, just return the result:
return total;
Put it all together and you got this:
private static int AddSum(string x1)
{
string[] numbers = x1.Split(',');
int total = 0;
foreach (string number in numbers)
{
total += int.Parse(number);
}
return total;
}
I hope this helps and clarifies things. Keep in mind that this method doesn't do any kind of error checking, so if your input is bad, you'll get an exception probably.

How to get ASCII value of characters in C#

Below is my string in C# which I am converting it to Character array & in need to get the ASCII value of each character in the string.
static void Main(string[] args)
{
string s = "Test";
var arr = s.ToCharArray();
foreach(var a in arr)
{
var n = Encoding.ASCII.GetByteCount(a.ToString());
Console.WriteLine(a);
Console.WriteLine(n);
}
}
This outputs as
T
1
e
1
s
1
t
1
On googling I got number of links but none of them suffice my need.
How to get ASCII value of string in C#
https://www.codeproject.com/Questions/516802/ConvertingpluscharsplustoplusASCIIplusinplusC
I am in need to get the ASCII value of each character in string.???
Any help/suggestion highly appreciated.
A string can be directly enumerated to a IEnumerable<char>. And each char can be casted to a integer to see its UNICODE "value" (code point). UTF-16 maps the 128 characters of ASCII (0-127) to the UNICODE code points 0-127 (see for example https://en.wikipedia.org/wiki/Code_point), so you can directly print this number.
string s = "Test";
foreach (char a in s)
{
if (a > 127)
{
throw new Exception(string.Format(#"{0} (code \u{1:X04}) is not ASCII!", a, (int)a));
}
Console.WriteLine("{0}: {1}", a, (int)a);
}
GetByteCount will return the count of bytes used, so for each character it will be 1 byte.
Try GetBytes
static void Main(string[] args)
{
string s = "Test";
var n = ASCIIEncoding.ASCII.GetBytes(s);
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine($"Char {s[i]} - byte {n[i]}");
}
}
Every character is represented in the ASCII table with a value between 0 and 127. Converting the chars to an Integer you will be able to get the ASCII value.
static void Main(string[] args)
{
string s = "Test";
for (int i = 0; i < s.Length; i++)
{
//Convert one by one every leter from the string in ASCII value.
int value = s[i];
Console.WriteLine(value);
}
}
You're asking for the byte count when you should be asking for the bytes themselves. Use Encoding.ASCII.GetBytes instead of Encoding.ASCII.GetByteCount. Like in this answer: https://stackoverflow.com/a/400777/3129333
Console.WriteLine(a);
Console.WriteLine(((int)a).ToString("X"));
You need to convert in int and then in hex.
GetByteCount will return the count of bytes used, so for each character it will be 1.
You can read also: Need to convert string/char to ascii values

How to split a number into individual nos

I have a int number = 1782901998 whose Length is 10 numbers; I need to split them into 10 different strings. I tried the following code, but it does not give back any output; I need to assign the each number to a string.
string number = 7894;
char[] numberChars = number.ToString().ToCharArray();
int[] digits = new int[numberChars.length];
for(int i = 0; i < numberChars.length; i++) {
digits[i] = (int)numberChars[i];
}
This code only returns 57 in digits list.
Because your code fills the array with the ASCII code for the characters of the number variable. You can use LINQ like below:
int[] digits = number.Select(c => Convert.ToInt32(c.ToString())).ToArray();
Or if you want to assign the each number to a string simply:
string[] digits = number.Select(c => c.ToString()).ToArray();

Binary to Decimal Conversion doesn't work

This is kind of a funky program. For some reason it works when the binary input is something like 101. Then it doesn't for 1000. This is kind of odd. Could someone please explain?
class Program
{
static void Main()
{
string binary = "xxx";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
Console.WriteLine("Length is: {0}", binary.Length);
if (binary[i] == 49) //Look at that
decimalValue = decimalValue + Math.Pow(2, i);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}
The heart of it is of course
if (binary[i] == 49)
I'm just making it to teach myself some C#. Could someone tell me what to put on the right side other than 49, which is the ASCII number for "1". If I put "1" I get an error saying you can't compare a string to a char.
Any help would be appreciated. I don't want to use the pre-canned convert to binary method, because this is supposed to be a teachable moment.
You read the characters from the wrong end.
As was said immediately in the first comment to the question, by Lucas Trzesniewski, replace one use of i (not both) inside the for loop with binary.Length - 1 - i.
The reason why it works for "101" is that this is a palindrome (reads the same backwards).
Note: 49 is the ASCII code for '1'. It is more readable to use == '1' than == 49. However, both work equally well. In C# you get a char value if you use single quotes, as in '1', and you get a string object reference if you use double quotes, "1".
You should remove the stuff with "xxx". It has no function. Just dostring binary = Console.ReadLine();.
Instead of trying to add the value of each individual bit based on it's position you could take another approach: shift and add. In this approach you shift the current value to the left (by multiplying that value by 2) and adding the current bit.
For instance: the binary value 1010 becomes decimal 10 in four cycles:
value = 0
value *= 2 => value = 0
value += bit 1 => value = 1
value *= 2 => value = 2
value += bit 0 => value = 2
value *= 2 => value = 4
value += bit 1 => value = 5
value *= 2 => value = 10
value += bit 0 => value = 10
Or, in code:
using System;
public class Program
{
public static void Main()
{
string binary = "";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
decimalValue *=2; // shift current value to the left
if (binary[i] == 49)
{
decimalValue += 1; // add current bit
}
Console.WriteLine("Current value: {0}", decimalValue);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}

Categories

Resources