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);
}
}
}
Related
I have a text file that looks like this
Words Words
Words Words
Words Words
1 34.4e+1
2 34.3e+1
3 34.2e+1
4 34.1e+1.... // and so on
I need to get the string number and concert it to decimal/double and then send it to an array where I can the use the array outside of the for loop to get the average via Enumerable.Chunk
decimal[] raw = new decimal[] { };
decimal[] rawAvgList = new decimal[] { };
decimal RawAvg = 0m;
try
{
string bPath = aPath + "\\" + fileName.Name + "\\textfilename.txt";
string[] readText = File.ReadAllLines(bPath);
readText = readText.Skip(3).ToArray();
foreach (var line in readText)
{
raw = new decimal[] { Decimal.Parse(line.Substring(9).ToString(), style1) };
for (int i = 0; i < raw.Length; i++)
{
Console.WriteLine("{0} \t {1}", raw[i], i++);
}
}
rawAvgList = raw.Chunk(20).Select(chunk => chunk.Average()).ToArray();
RawAvg = rawAvgList.Average();
}
So for when I call the array outside of the loop it only grabs the last number in the text file. Am I calling the information wrong? I swear I have tried all the different way to call the numbers from the text file and I just keep running into errors. The error range from it not liking me using skip and substring at the same time or and enumerable error where it returned the error and not the number. Anything to help, Thanks!
You are assigning the variable raw to a new value on each loop iteration, wiping out any value that was stored previously. The end result is that after the loop terminates, it will only contain the value from the last line in the file as you are seeing.
You can declare raw as a List<decimal> instead, then within the loop, you would do
raw.Add(Decimal.Parse(line.Substring(9).ToString(), style1));
This way, once the loop finishes, you'll have all the numbers and not just the last one.
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()
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);
}
}
}
}
}
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);