Problem in reading numbers - c#

Hello friends i am a total beginner in c#.
I want to read numbers in the following format
2
1 10
3 5
For reading 2 i have used Convert.ToInt32(Console.ReadLine()) method and successfully stored it. But for the next input i want to read the number and after a space i want to read another number. I cannot use ReadLine() method.. I have used Convert.ToInt32(Console.Read())
But the number 1 is read as 49
So How do i achieve reading numbers
In java i have found a similar class called Scanner which contains methods line nextInt()
Is there any C# equivalent to that class.
In short i just want to know how to read and store numbers(integers or floats) in C#.

You can use ReadLine() and just split on whitespace, i.e.,
void Main( string[] args )
{
var numbers = new List<int>();
while(whatever)
{
var input = Console.ReadLine();
var lines = input.Split(
new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries
);
foreach( var line in lines )
{
int result;
if( !int.TryParse( line, out result ) )
{
// error handling
continue;
}
numbers.Add( result );
}
}
}

You can use the Split method, to break the line into numbers.
while (true)
{
var s = Console.ReadLine();
if (s == null) break;
foreach (var token in s.Split(' '))
{
int myNumber = int.Parse(token);
// ... do something ....
}
}

You problem is about converting strings into integers, as Console.Readline always returns a string.
There are many ways to parse multiple ints, but you will basically need to split the string using some method. I don't know of a Scanner in C# (but I guess you should seach for some kind of tokenizer to find it, since this would be the standard name.
Writing one is not that hard, especially if you only expect integers to be separated by spaces. Implementing it in a method could be something like
// Optional seperators
public IEnumerable<int> ParseInts(string integers, params char[] separators)
{
foreach (var intString in integers.Split(separators))
{
yield return int.Parse(intString);
}
}
public IEnumerable<int> ParseInts(string integers)
{
return ParseInts(integers, ' ');
}

Use this
string[] lines = File.ReadAllLines("Path to your file");
foreach (string line in lines)
{
if (line.Trim() == "")
{
continue;
}
string[] numbers = line.Trim().Split(' ');
foreach (var item in numbers)
{
int number;
if (int.TryParse(item, out number))
{
// you have your number here;
}
}
}

I've been doing this on HackerRank a lot, here's a helper method I use for reading an array of integers:
static int [] StringToIntArray(string s) {
string [] parts = s.Split(' ');
int [] arr = new int[parts.Length];
for (int i = 0; i < arr.Length; i++) {
arr[i] = Convert.ToInt32(parts[i]);
}
return arr;
}
Here's a sample reading two numbers on one line, then two lines with those many numbers into arrays:
string [] parts = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(parts[0]);
int m = Convert.ToInt32(parts[1]);
int [] a = StringToIntArray(Console.ReadLine());
int [] b = StringToIntArray(Console.ReadLine());
Sample input:
3 5
40 50 60
10 20 30 100 7500

Related

Convert strings to floats or double from a list c#

I'm trying to convert all the number from a list of strings to float. I'm not sure why all the items from the list are char, and it converts every single digit to char instead of converting the number until space. Below is the code. If the first input is 2, it will create 2 lists, let's say 12 23 33 and 22 33 44.
From list 1, I need mm to be 12/23/33 instead of 1/2/2/3/3/3
int nrMagazine = Convert.ToInt32(Console.ReadLine());
List<String> mag = new List<String>();
string prop = "";
for(int i = 0; i < nrMagazine;i++)
{
string profitTrimestre = Console.ReadLine();
profitTrimestre.Split();
mag.Add(profitTrimestre);
//cel mai profitabil trimestru,trimestru 1 = m[0],1=m[1]
//cel mai profitabil magazin,mag 1,2,3,4,n
}
foreach(string m in mag)
{
foreach(string mm in m)
{
Console.WriteLine(mm);
}
}
There are multiple problems in your current code.
I m not sure why all the items from the list are char
Because you have another loop for string which implicitly using enumerator iterates the string by character. You should be able to convert to float by using Convert class :
foreach(string m in mag)
{
var number = Convert.ToDouble(m);
}
Secondly if numbers are space delimited then use Split overload that takes character to use for splitting :
var splitted = profitTrimestre.Split(new char[]{' '}, StringSplitOption.RemoveEmptyEntries);
and then loop :
foreach(var item in splitted)
mag.Add(item);
you can try this
public static void Main(string[] args)
{
var text = Console.ReadLine();
var strings = text.Split(' '); // This splits the 11 22 33 to three string values.
var numbers = strings.Select(a =>
{
if (float.TryParse(a, out float number))
return number;
return 0;
}).ToList(); // This converts 3 strings to 3 float
}
Or you can try the shortest version (thanks to Prasad Telkikar)
public static void Main(string[] args)
{
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), x => float.TryParse(x, out float number) ? number : 0);
}
Maybe you just need to split your line on spaces instead and actually assign the split value to mag?
string[] mag = profitTrimestre.Split(' ');
Then you should be able to loop over each string in that list with just one foreach:
foreach(string m in mag)
{
Console.WriteLine(m);
}
If you want to convert the individual string parts to Doubles, you can do that like this:
double d = double.Parse(m);
You can also do it like this, if you want to avoid exceptions if the strings aren't valid double representations:
double.TryParse(m, out double d);
profitTrimestre.Split(); will return an array, which currently you're doing nothing with it. Try change to this instead:
Console.WriteLine("Insert the number of lists: ");
if(int.TryParse(Console.ReadLine(),out int nrMagazine)) //Never trust user's inputs
{
List<string> mag = new List<string>();
for(int i = 0; i < nrMagazine;i++)
{
Console.WriteLine($"Insert List {i+1}: ");
mag.Add(Console.ReadLine());
}
foreach(string m in mag) //iterates over each input string
{
foreach(string mm in m.Split(' ')) //splits each entry and iterates over the itens
{
Console.WriteLine(mm);
if(double.TryParse(mm, out double myDouble)) //You can also pass a Culture
{
//Do something with your double
}
else
{
//Input not a double in the current culture
}
}
}
}
else
{
Console.WriteLine("The input was not an integer");
}
I guess that's what you need.
Dictionary<int, IEnumerable<float>> nrMagazine = new Dictionary<int, IEnumerable<float>>(); //creates dictionary
int.TryParse(Console.ReadLine(), out int x); //input number for iterations here
for (int i = 0; i < x; i++)
{
nrMagazine.Add(i, Console.ReadLine().Split(' ').Select(s => { float.TryParse(s, out float y); return y; })); //builds floats list and adds it to dictionary x times
}
nrMagazine.Keys.ToList().ForEach((i) => Console.WriteLine("Magazine: " + i + ", Profits: " + String.Join(", ", nrMagazine[i]))); //prints items from dictionary

Different pattern to give input in console application

I am a beginner in .net and I made a simple console application and it's works. My problem is when I give input the input must be in new line
eg:
1
2
3
how I input like
1 2
3
I am using the following code
int a, b, c,d;
Console.WriteLine("Enter the numbers:");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = a + b + c;
Console.WriteLine("Sum:" + d);
Write an input parser... ReadLine, split the resulting string by space character and feed each segment into int converter and sum them.
Example given below is taking advantage of Linq which is a bit functional and allow chaining something like the token array resulting from the split and performs operations on each of its elements. I.e. Select(...) is basically a map function that will apply Convert.ToInt32 to each elements in the token array and then pipe that into the Aggregate function that memoize the result so far (starting from 0 and keep adding the next element in the now converted int token array ... represented by s + t where s is current memoized seed and t is the current token in the iteration.)
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var str = Console.ReadLine();
var tokens = str.Split(' ');
var result = tokens.Select(t => Convert.ToInt32(t)).Aggregate(0, (s, t) => s + t);
Console.WriteLine(result);
}
}
For completeness sake... This second version should be more resistant to error:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter 1 or more numbers separated by space in between. I.e. 1 2\nAny non numerical will be treated as 0:");
var str = Console.ReadLine();
if (string.IsNullOrWhiteSpace(str))
{
Console.WriteLine("Sorry, expecting 1 or more numbers separated by space in betwen. I.e. 5 6 8 9");
}
else
{
var tokens = str.Split(' ');
var result = tokens
.Select(t =>
{
int i;
if (int.TryParse(t, out i))
{
Console.WriteLine("Valid Number Detected: {0}", i);
};
return i;
})
.Aggregate(0, (s, t) => s + t);
Console.WriteLine("Sum of all numbers is {0}", result);
}
Console.ReadLine();
}
}
You are using Console.ReadLine() which reads the whole line.
Documentation:
A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s).
You can read whole line and then process it, for example with String.Split method.
One option would be to accept a single line of input as a string and then process it. For example:
//Read line, and split it by whitespace into an array of strings
//1 2
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
Here's an exmaple :
class Program
{
private static void Main(string[] args)
{
int a = 0,
b = 0;
Console.WriteLine("Enter the numbers:");
var readLine = Console.ReadLine();
if (readLine != null)
{
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if (new Regex(#"^\d+\s+\d+$").IsMatch(readLine))
{
string[] tokens = readLine.Split();
//Parse element 0
a = int.Parse(tokens[0]);
//Parse element 1
b = int.Parse(tokens[1]);
}
else
{
Console.WriteLine("Please enter numbers");
}
}
var c = Convert.ToInt32(Console.ReadLine());
var d = a + b + c;
Console.WriteLine("Sum:" + d);
}
}

Read numbers from the console given in a single line, separated by a space

I have a task to read n given numbers in a single line, separated by a space ( ) from the console.
I know how to do it when I read every number on a separate line (Console.ReadLine()) but I need help with how to do it when the numbers are on the same line.
You can use String.Split. You can provide the character(s) that you want to use to split the string into multiple. If you provide none all white-spaces are assumed as split-characters(so new-line, tab etc):
string[] tokens = line.Split(); // all spaces, tab- and newline characters are used
or, if you want to use only spaces as delimiter:
string[] tokens = line.Split(' ');
If you want to parse them to int you can use Array.ConvertAll():
int[] numbers = Array.ConvertAll(tokens, int.Parse); // fails if the format is invalid
If you want to check if the format is valid use int.TryParse.
You can split the line using String.Split():
var line = Console.ReadLine();
var numbers = line.Split(' ');
foreach(var number in numbers)
{
int num;
if (Int32.TryParse(number, out num))
{
// num is your number as integer
}
}
You can use Linq to read the line then split and finally convert each item to integers:
int[] numbers = Console
.ReadLine()
.Split(new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray();
You simply need to split the data entered.
string numbersLine = console.ReadLine();
string[] numbers = numbersLine.Split(new char[] { ' '});
// Convert to int or whatever and use
This will help you to remove extra blank spaces present at the end or beginning of the input string.
string daat1String = Console.ReadLine();
daat1String = daat1String.TrimEnd().TrimStart();
string[] data1 = daat1String.Split(null);
int[] data1Int = Array.ConvertAll(data1, int.Parse);
you can do
int[] Numbers = Array.ConvertAll(Console.ReadLine().Split(' '),(item) => Convert.ToInt32(item));
the above line helps us get individual integers in a Line , separated by a
Single space.Two Or More spaces between numbers will result in error.
int[] Numbers = Array.ConvertAll(Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), (item) => Convert.ToInt32(item));
this variation will Fix the error and work well even when two or more spaces between numbers in a Line
you can use this function, it's very helpful
static List<string> inputs = new List<string>();
static int input_pointer = 0;
public static string cin(char sep = ' ')
{
if (input_pointer >= inputs.Count)
{
string line = Console.ReadLine();
inputs = line.Split(sep).OfType<string>().ToList();
input_pointer = 0;
}
string v = inputs[input_pointer];
input_pointer++;
return v;
}
Example:
for(var i =0; i<n ; i++)
for (var j = 0; j<n; j++)
{
M[i,j] = Convert.ToInt16(cin());
}

How to extgract an integer and a two dimensional integer array from a combination of both in C#

I have an input as
2:{{2,10},{6,4}}
I am reading this as
string input = Console.ReadLine();
Next this input has to be passed to a function
GetCount(int count, int[,] arr)
{
}
How can I do so using C#?
Thanks
You could use RegularExpressions for extracting in an easy way each token of your input string. In the following example, support for extra spaces is included also (the \s* in the regular expressions).
Remember that always is a great idea to give a class the responsibility of parsing (in this example) rather than taking an procedural approach.
All the relevant lines are commented for better understanding.
Finally, i tested this and worked with the provided sample input strings.
using System;
using System.Text.RegularExpressions;
namespace IntPairArrayParserDemo
{
class Program
{
static void Main(string[] args)
{
var input = "2:{{2,10},{6,4}}";
ParseAndPrintArray(input);
var anotherInput = "2 : { { 2 , 10 } , { 6 , 4 } }";
ParseAndPrintArray(anotherInput);
}
private static void ParseAndPrintArray(string input)
{
Console.WriteLine("Parsing array {0}...", input);
var array = IntPairArrayParser.Parse(input);
var pairCount = array.GetLength(0);
for (var i = 0; i < pairCount; i++)
{
Console.WriteLine("Pair found: {0},{1}", array[i, 0], array[i, 1]);
}
Console.WriteLine();
}
}
internal static class IntPairArrayParser
{
public static int[,] Parse(string input)
{
if (string.IsNullOrWhiteSpace(input)) throw new ArgumentOutOfRangeException("input");
// parse array length from string
var length = ParseLength(input);
// create the array that will hold all the parsed elements
var result = new int[length, 2];
// parse array elements from input
ParseAndStoreElements(input, result);
return result;
}
private static void ParseAndStoreElements(string input, int[,] array)
{
// get the length of the first dimension of the array
var expectedElementCount = array.GetLength(0);
// parse array elements
var elementMatches = Regex.Matches(input, #"{\s*(\d+)\s*,\s*(\d+)\s*}");
// validate that the number of elements present in input is corrent
if (expectedElementCount != elementMatches.Count)
{
var errorMessage = string.Format("Array should have {0} elements. It actually has {1} elements.", expectedElementCount, elementMatches.Count);
throw new ArgumentException(errorMessage, "input");
}
// parse array elements from input into array
for (var elementIndex = 0; elementIndex < expectedElementCount; elementIndex++)
{
ParseAndStoreElement(elementMatches[elementIndex], elementIndex, array);
}
}
private static void ParseAndStoreElement(Match match, int index, int[,] array)
{
// parse first and second element values from the match found
var first = int.Parse(match.Groups[1].Value);
var second = int.Parse(match.Groups[2].Value);
array[index, 0] = first;
array[index, 1] = second;
}
private static int ParseLength(string input)
{
// get the length from input and parse it as int
var lengthMatch = Regex.Match(input, #"(\d+)\s*:");
return int.Parse(lengthMatch.Groups[1].Value);
}
}
}
Not to do your work for you, you will first have to parse the whole string to find the individual integers, either using regular expressions or, as I would do it myself, the string.Split method. Then parse the substrings representing the individual integers with the int.Parse or the int.TryParse methods.
I doubt you're going to get a serious parsing answer for your custom format. If you NEED to have the value inputted that way, I'd look up some info on regular expressions. If that's not powerful enough for you, there are some fairly convienient parser-generators you can use.
Alternatively, the much more realistic idea would be something like this:
(NOTE: Haven't tried this at all... didn't even put it in VS... but this is the idea...)
int rows = 0;
string rowsInput = "";
do {
Console.Write("Number of rows:");
rowsInput = Console.ReadLine();
} while (!Int32.TryParse(rowsInput, out rows);
int columns = 0;
string columnsInput = "";
do {
Console.Write("Number of columns:");
string columnsInput = Console.ReadLine();
} while (!Int32.TryParse(columnsInput, out columns);
List<List<int>> values = new List<List<int>>();
for (int i = 0; i < rows; i++)
{
bool validInput = false;
do {
Console.Write(String.Format("Enter comma-delimited integers for row #{0}:", i.ToString()));
string row = Console.ReadLine();
string[] items = row.split(',');
int temp;
validInput = (items.Length == columns) && (from item in items where !Int32.TryParse(item, out temp) select item).count() == 0;
if (validInput)
{
values.add(
(from item in items select Convert.ToInt32(item)).ToList()
);
}
} while (!validInput);
}

How to get number from string in C#

i have a String in HTML (1-3 of 3 Trip) how do i get the number 3(before trip) and convert it to int.I want to use it as a count
Found this code
public static string GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
return (m.Value);
}
But it can only get 1 number
Regex is unnecessary overhead in your case. try this:
int ExtractNumber(string input)
{
int number = Convert.ToInt32(input.Split(' ')[2]);
return number;
}
Other useful methods for Googlers:
// throws exception if it fails
int i = int.Parse(someString);
// returns false if it fails, returns true and changes `i` if it succeeds
bool b = int.TryParse(someString, out i);
// this one is able to convert any numeric Unicode character to a double. Returns -1 if it fails
double two = char.GetNumericValue('٢')
Forget Regex. This code splits the string using a space as a delimiter and gets the number in the index 2 position.
string trip = "1-3 of 3 trip";
string[] array = trip.Split(' ');
int theNumberYouWant = int.Parse(array[2]);
Try this:
public static int GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, #"^.*of\s(?<TripCount>\d+)");
return m.Groups["TripCount"].Length > 0 ? int.Parse(m.Groups["TripCount"].Value) : 0;
}
Another way to do it:
public static int[] GetNumbersFromString(string str)
{
List<int> result = new List<int>();
string[] numbers = Regex.Split(input, #"\D+");
int i;
foreach (string value in numbers)
{
if (int.TryParse(value, out i))
{
result.Add(i);
}
}
return result.ToArray();
}
Example of how to use:
const string input = "There are 4 numbers in this string: 40, 30, and 10.";
int[] numbers = MyHelperClass.GetNumbersFromString();
for(i = 0; i < numbers.length; i++)
{
Console.WriteLine("Number {0}: {1}", i + 1, number[i]);
}
Output:
Number: 4
Number: 40
Number: 30
Number: 10
Thanks to: http://www.dotnetperls.com/regex-split-numbers
If I'm reading your question properly, you'll get a string that is a single digit number followed by ' Trip' and you want to get the numeric value out?
public static int GetTripNumber(string tripEntry)
{
return int.Parse(tripEntry.ToCharArray()[0]);
}
Not really sure if you mean that you always have "(x-y of y Trip)" as a part of the string you parse...if you look at the pattern it only catches the "x-y" part thought with the acceptance of .Ee+- as seperators. If you want to catch the "y Trip" part you will have to look at another regex instead.
You could do a simple, if you change the return type to int instead of string:
Match m = Regex.Match(str, #"(?<maxTrips>\d+)\sTrip");
return m.Groups["maxTrips"].Lenght > 0 ? Convert.ToInt32(m.Groups["maxTrips"].Value) : 0;

Categories