While working on a basic coding challenge I have come across a confusing situation that i am unable to fathom the cause of (I am new to programming)
whilst attempting to split a number into its individual digits, my int array contains the value 13 but returns the value 49??
there is probably an obvious reason for this and if so i apologize.
I have found an alternate way to split my numerical string into individual digits but would still like to know what i was doing wrong
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddTheDigits
{
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("TextFile1.txt"))
{
//int total = 0;
string line = reader.ReadLine();
//Console.WriteLine(line); //testing
char[] charArray = line.ToCharArray(0,1);
int[] intArray = new int[charArray.Length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = Convert.ToInt32(charArray[i]);
Console.Write(intArray[i]);
}
}
Console.ReadLine();
}
}
}
You are probably mixing up the ASCII code for the digits with the digits themselves. Try replacing
intArray[i] = Convert.ToInt32(charArray[i]);
with
intArray[i] = charArray[i] - '0';
and see if that helps.
you're taking you line (Which probably contains '13'), and grabbing the first char in it (line.ToCharArray(0,1);). You then convert this char (which has the numerical value 49, equal to '1' in UTF-16) to an int (still equals 49) and you print it. That's it. the '3' is left out due to the ToCharArray only grabbing the first character.
What you are doing is essentially:
"13".ToCharArray(0,1);
which will give you the same value as :
char c = '1';
which is 49, the ASCII code for '1'
49 is ASCII code for 1.
Instead of using Int32.Convert, you should use Int32.Parse.
Related
I have a question related to filling it in an array. In the program I have to write I am given "input from user: different number of numbers separated by space (for example: 1 4 6 2)". These numbers must be entered in an array that will be used later.
The problem is the following how to insert in the array an indefinite number of numbers written on one line with space between them without determining their number in advance?
I think the easier thing to do would be to split input string by space and then use Linq to map each element to an int:
String userInput = "1 4 6 2";
int[] ints = userInput.Split(' ').Select(x => Int32.Parse(x)).ToArray();
this is the answer to my question. I wish I had helped someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Stack_Sum
{
class Program
{
static void Main(string[] args)
{
Stack<int> numbers = new Stack<int>();
string input = Console.ReadLine();
string[] number = Regex.Split(input, #"\D+");
foreach (string value in number)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
}
}
}
I just started to learn C# and already have a question, maybe quite dumb.
I'm writing a little desktop program (Windows Forms) that checks whether entered bank account number is valid or computes missing control numbers. To check number validity we must multiply each digit in that number by corresponding factor. My problem is:
When I enter whole number (26 digits) in TextBlock control and click Check button I need to parse that number into int array somehow. I saw some examples already and tried
int[] array = new int[26];
char[] sep = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
String[] numbers = inputWindow.Text.Split(sep);
for (int i = 0; i < 26; i++)
array[i] = Int32.Parse(numbers[i]);
But got FormatException. I also tried
array = inputWindow.Text.Split().Select(h => Int32.Parse(h)).ToArray());
Or something similar but got OverflowException. Int64.Parse resulted in obvious type conversion error. How to accomplish that parsing?
Thanks in advance
EDIT
My bad, there was 30 instead of 26, but that actually didn't matter.
That second snippet is almost there (assuming you want an array of numbers, and that the Text property has only numbers in it).
Remove the call to Split(), and the Select() portion will iterate over each character in the string.
var array = inputWindow.Text.Select(i => Convert.ToInt32(i-48)).ToArray();
I just did this in a console application and I was able to get the numbers into the array. I did no math on each one. I assume you could take it from there. I also recommend using a List instead of an array so the size is not fixed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number: ");
string inputStr = Console.ReadLine();
int[] array = new int[30];
int i = 0;
foreach(Char c in inputStr)
{
array[i] = Convert.ToInt32(c.ToString());
i++;
}
Console.WriteLine("");
foreach (int num in array)
{
Console.WriteLine(num.ToString());
}
Console.ReadLine();
}
}
}
Your whole number just 26 digits,but your i set max is 30 for (int i = 0; i < 30; i++), 26 is less than 30,so array[i] = Int32.Parse(numbers[i]) throw OverflowException
This code snippet can be used to convert TextBox text to integer array. But you have to make sure that user will input only interger in textBox.
int[] array = new int[30];
char[] sample = textBox1.Text.ToCharArray();
for (int i = 0; i < 26; i++)
array[i] = int.Parse(sample[i].ToString());
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.
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();
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);