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);
}
}
}
}
}
Related
Is it possible to read the elements of an array from the same line (from Console) in C#? I know it's possible to read multiple inputs from the console and storing the individual parts in different variables using Split(). But I can't understand how to do it in arrays.
Code
for (int i = 0; i < arrival.Length; i++)
{
arrival[i] = int.Parse(Console.ReadLine());
}
For example, I have to enter the elements 34 35 36 37 in the array. If I use the above mentioned code, I have to enter each element in a separate line. But what I need is, if I enter 34 35 36 37 in the Console, it must store each number as an element in the array. How to do this?
you can do it in following manner for array of type integer
string readLine=Console.ReadLine());
string[] stringArray=readLine.split(' ');
int[] intArray = new int[stringArray.Length];
for(int i = 0;i < stringArray.Length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others
intArray[i] = int.parse(stringArray[i]);
}
I am not clear with question, may be you are looking for this
using System;
class Program
{
static void Main()
{
string s = "there is a cat";
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
Output will be
there
is
a
cat
Ref link - http://www.dotnetperls.com/split
you need to read from console, split the input string, convert the splitted strings to your type (here to double), then add them to your own array:
here is the code doing what you want:
using System;
using System.Collections.Generic;
using System.Linq;
namespace test4
{
class Program
{
static void Main(string[] args)
{
List<double> arrayOfDouble = new List<double>(); // the array to insert into from console
string strData = Console.ReadLine(); // the data, exmple: 123.32, 125, 78, 10
string[] splittedStrData = strData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// trim then parse to souble, then convert to double list
List<double> dataArrayAsDouble = splittedStrData.Select((s) => { return double.Parse(s.Trim()); }).ToList();
// add the read array to your array
arrayOfDouble.AddRange(dataArrayAsDouble);
}
}
}
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.
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);