This question already has answers here:
Convert string to int array using LINQ [duplicate]
(6 answers)
Closed 7 years ago.
I have lines (string type) of numbers like "23 78 53 4 94 32 148 31". I need to put them into int array. Here's the lame code I wrote, but it doesn't work properly:
int currentArrayValue=0;
int currentChar=0;
for (int i = 0; i < text1.Length; i++)
{
if (text1[i] != ' ')
{
currentChar++;
continue;
}
else
{
for (int k = 1; k <=currentChar; k++)
{
if (k == 1) Array[currentArrayValue] = text1[i - currentChar];
else if (k == 2) Array[currentArrayValue] = text1[i - currentChar] * 10;
else if (k == 3) Array[currentArrayValue] = text1[i - currentChar] * 100;
}
currentArrayValue++;
}
}
It can be a one-, two- or three-digit number.
There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use TryParse:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var test = "1 2 3 x";
var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
var results = new List<int>();
foreach(var value in values)
{
int x;
if(Int32.TryParse(value, out x))
{
results.Add(x);
}
else
{
Console.WriteLine("{0} is not an integer", value);
}
}
}
}
So if you have a string as such and all the numbers are separated by spaces
string foo = "12 34 567 120 12";
All you have to do is use string.Split(' ') to break this string into an array then convert those values to int values.
int[] intArray = foo.Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
string input = "23 78 53 4 94 32 148 31";
var arr = Regex.Matches(input, #"\d+").Cast<Match>().Select(m => int.Parse(m.Value)).ToArray();
Use string.Split instead. You can split on each space and get an array. From there, parse each item to an int. You can actually do it all in one line with LINQ.
int[] myInts = text1.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => int.Parse(s)).ToArray();
Non-Linq answer
const string inputVal = "23 78 53 4 94 32 148 31";
string[] splitInput = inputVal.Split(' ');
int[] inputIntArray = new int[splitInput.Length];
int counter = 0;
foreach (string split in splitInput){
inputIntArray[counter++] = int.Parse(split);
}
Related
So I have a code here and what I am tring to do is to get max and min value from string("1 2 3 4 5 6 66") and when I tried to make a char array from this string and get from it max and min I am getting 54 as a max and 32 as a min. HOW?
static void Main(string[] args)
{
HighAndLow("1 2 3 4 5 6 66");
}
public static string HighAndLow(string numbers)
{
char[] liczby = numbers.ToArray();
int max = liczby.Max();
int min = liczby.Min();
Console.WriteLine($"{max} {min}");
return $"{max} {min}";
}
You're getting the char codes, not the values.
Change
char[] liczby = numbers.ToArray();
to something like
char[] temp = numbers.Split(' ');
int[] liczby = temp.Select(c => int.parse(c)).ToArray();
Look here
https://www.asciitable.com/
You will see that the character 'c' is decimal 54
and that " " (space) has decimal value 32
using System;
using System.Collections.Generic;
using System.Linq;
namespace stack
{
internal class Program
{
static void Main(string[] args)
{
HighAndLow("1 2 3 4 5 6 66");
}
static string HighAndLow(string numbers)
{
if (numbers.Length > 0)
{
var listnumbers = numbers.Split(' ');
var max = int.MinValue;
var min = int.MaxValue;
foreach (var number in listnumbers)
{
var ent = int.Parse(number);
max = ent <= max ? max : ent;
min = ent >= min ? min : ent;
}
Console.WriteLine("max :"+max+" min: "+min);
return $"{max} {min}";
}
return "empty string";
}
}
}
or just replace :
char[] liczby = numbers.ToArray();
with :
var temp = numbers.Split(' ');
int[] liczby = temp.Select(c => int.Parse(c)).ToArray();
I'm trying to receive an integer of 40 characters as a string from the console and iterate over each element in that string and then save it as an element in an array of int's. this is not working and just returns 49 50 51 as array members.
public HugeInteger(string myString)
{
for (int i = 0; i < 39; i++)
{
int t = Convert.ToInt16(myString[i]);
this.myInteger[i] = t;
}
}
Since you are trying to convert chars '0' .. '9' to integers, you just need to subtract the character code for '0' from each character, like so:
public HugeInteger(string myString)
{
for (int i = 0; i < 39; i++)
{
char c = myString[i];
// Remove the next `if` (and its body) if error checking is not required.
if (c < '0' || c > '9')
throw new InvalidOperationException("Non-digit in input");
this.myInteger[i] = c - '0';
}
}
This works because:
The character codes for '0' to '9' are 48 .. 57
If you subtract '0' from a character code, you are effectively subtracting 48 from it.
Therefore subtracting '0' from a digit character will yield the int equivalent.
Note that there is no error checking in your loop, so if the string contains any non-digit characters, the result will be wrong!
If you want the string to be converted to an array i would suggest that you convert the string to char array and then convert back to int[] like below:
class Program
{
static void Main(string[] args)
{
string myString = "1231654165152112315461561561651561562165";
var charArray = myString.ToCharArray();
foreach (var item in charArray)
{
Console.WriteLine(item);
}
int[] myStringIntegers = Array.ConvertAll(charArray, c => (int)Char.GetNumericValue(c));
Console.WriteLine(myStringIntegers.Length);
int i = 0;
foreach (var item in myStringIntegers)
{
Console.WriteLine("Value at pos("+i+") : " + item);
i++;
}
Console.Read();
}
}
if you have multi digit numbers then i would say that you have the myString value separated by a comma ',' or space or whatever you like.
CAUTION : If the value is non-numeric then it will result in code failure. So you need to make a regex check or some sort of validation to address non-numeric inputs
Below is 2 simple ways of extracting an array of integers from a string.
Converting char to int.
Converting a split string to int.
This may not be the best or most elegant solution but you can get some idea on how you would want to approach your problem.
class Program
{
static void Main(string[] args)
{
Console.Write("Input str: ");
string str = Console.ReadLine();
int[] numbers = StringToIntArray(str);
foreach(int num in numbers)
{
Console.WriteLine(num);
}
Console.Write("Input str: ");
str = Console.ReadLine();
Console.Write("Input split char: ");
ConsoleKeyInfo splitChar = Console.ReadKey();
numbers = StringToIntArray(str, splitChar.KeyChar);
Console.WriteLine();
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Console.ReadKey();
}
public static int[] StringToIntArray(string str, char? splitChar = null)
{
List<int> numbers = new List<int>();
if (splitChar.HasValue)
{
string[] split = str.Split(splitChar.Value);
foreach(string splitStr in split)
{
int parsedInt = 0;
if (int.TryParse(splitStr, out parsedInt))
{
numbers.Add(parsedInt);
}
}
}
else
{
foreach (char c in str)
{
int parsedInt = 0;
if (int.TryParse(c.ToString(), out parsedInt))
{
numbers.Add(parsedInt);
}
}
}
return numbers.ToArray();
}
}
Output:
If your input is like this :
"1 2 3 4"
You should split it with ' ' or else you should separate your numbers with a separator.
List<int> myInteger=new List<int>();
public void HugeInteger(string myString)
{
foreach (string value in myString.Split(' '))
{
myInteger.Add(int.Parse(value));
}
}
Without seperator you should iterate by this way:
foreach (char c in myString)
{
myInteger.Add(int.Parse(c.ToString()));
}
static void Main(string[] args)
{
Console.WriteLine("Input number");
string myStr = Console.ReadLine();
int[] intNums = new int[40];
string flag = "";
for (int i = 0; i < myStr.Length; i++)
{
int a = 1;
flag = myStr.Substring(i, a);
a = i;
intNums[i] = Convert.ToInt32(flag);
a = i;
}
foreach (var item in intNums)
{
if (item > 0)
{
Console.Write(item+",");
}
}
Console.ReadKey();
}
IF you take an input you should sub-string the string, convert each part to an int, and then store in the array. Not sure a 40 character long integer would work just with the number bits even int64 can handle
This question already has answers here:
Finding longest word in string
(4 answers)
Closed 3 years ago.
I got an assignment to make a method to find the longest word in a string without split, distinct and foreach.
I was able to split the words and count the length but I am stuck on how can I actually compare and write them out.
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
longestWord(s1);
Console.
}
static void longestWord(String s1)
{
char emp = ' ';
int count = 0;
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
count++;
Console.Write(" " + (count-1));
Console.WriteLine();
count = 0;
}
else
{
Console.Write(ee[i]);
count++;
}
}
}
The output right now looks like this:
Alex 4
has 3
2 1
hands 5
I am pretty sure I would be able to get only the longest number to show by comparing count before reset with temp int but how to write out the word with it.
Or if there is a easier way which probably is.
You are already on a good way. Instead of directly printing the words, store the length and position of the longest word and print it at the end. Like so:
static void longestWord(String s1)
{
char emp = ' ';
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] == emp || s1[i] == '.')
{
// calculate the current word length
int currentLength = i - currentStart;
// test if this is longer than the currently longest
if(currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
// a new word starts at the next character
currentStart = i + 1;
}
}
// print the longest word
Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}
There is no need for the .ToCharArray(). You can access the string directly.
I will question whether you are actually supposed to treat "2" as a word and count it at all. Using regular expressions will allow you to approach the problem using a LINQ one-liner:
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
var word = longestWord(s1);
Console.WriteLine(word);
//Console.ReadLine();
}
static string longestWord(string s1) {
return Regex.Matches(s1,"[A-Za-z]+") // find all sequences containing alphabetical characters, you can add numberas as well: [A-Za-z0-9]
.Cast<Match>() // cast results to Enumberable<Match> so we can apply LINQ to it
.OrderByDescending(m => m.Length) // luckily for us, Match comes with Length, so we just sort our results by it
.Select(m => m.Value) // instead of picking up everything, we only want the actual word
.First(); // since we ordered by descending - first item will be the longest word
}
You can store for every word the chars in new list of chars (list for dynamic length)
and if the new word is longer of the prev long word convert it to string.
If you have two word in same length it will take the first.
If you want the last change the "maxLength < count" to "maxLength <= count"
static string longestWord(String s1)
{
char emp = ' ';
int count = 0;
int maxLength = 0;
string maxWord = string.Empty;
List<char> newWord = new List<char>();
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
if (maxLength < count)
{
maxLength = count;
maxWord = new string(newWord.ToArray());
}
count = 0;
newWord = new List<char>();
}
else
{
newWord.Add(ee[i]);
count++;
}
}
return maxWord;
}
The program must sum the even and odd numbers and then multiply them.
The problem comes when I enter the numbers like this 12345.
The array takes the number like 1 element but in order to make my code work it must separate the input when I put it like this 12345.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab_Methods
{
class Program
{
static void Main(string[] args)
{
int[] number = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int even = 0;
int odd = 0;
for (int i = 0; i < number.Length; i++)
{
if (number[i] % 2 == 0)
{
even = even + number[i];
}
else
{
odd = odd + number[i];
}
}
Console.WriteLine(even * odd);
}
}
}
If you want to split on ' ' (space), your input should use delimiter: "1 2 3 4 5"
// Separated input like "1 2 3 45 6 789"
// we don't have to materialize into array
// let's be nice: allow tabulation as well as space,
// tolerate leading/trailing and double spaces: " 1 2 3 "
var numbers = Console
.ReadLine()
.Split(new char[] { ' ', '\t'}, StringSplitOptions.RemoveEmptyEntries) // let's be nice
.Select(item => int.Parse(item));
int even = 0;
int odd = 0;
foreach (var number in numbers) {
if (number % 2 != 0)
odd += number;
else
even += number;
}
Console.WriteLine(even * odd);
If you want to enumerate digits within single number (e.g. within "12345")
// Single number input like "12345678"
var numbers = Console
.ReadLine()
.Where(c => c >= '0' && c <= '9') // characters in '0'..'9' range
.Select(c => c - '0'); // corresponding ints
// Then as usual
int even = 0;
int odd = 0;
foreach (var number in numbers) {
if (number % 2 != 0)
odd += number;
else
even += number;
}
Console.WriteLine(even * odd);
This way you will be able to input numbers from 0 to 9 without having to care about the way they are written:
class Program
{
static void Main(string[] args)
{
int[] numbers = Console.ReadLine().Select(x => {
if(int.TryParse(x.ToString(), out int result))
{
return result;
}
else
{
return -1;
}
}).Where(x => x != -1).ToArray();
int even = 0;
int odd = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] % 2 == 0)
{
even = even + numbers[i];
}
else
{
odd = odd + numbers[i];
}
}
Console.WriteLine(even * odd);
}
}
Input:
12345
Output:
54
Input:
1 2 3 4 5
Output:
54
Input:
1,2,3,4,5
Output:
54
Input:
,1.2 34|5
Output:
54
I'm trying to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11 right?
Here's my code:
static void Main(string[] args)
{
Console.WriteLine("Enter a Number");
int numb = int.Parse(Console.ReadLine());
int reverse = 0;
while (numb > 0)
{
int rem = numb % 10;
reverse = (reverse * 10) + rem;
numb = numb / 10;
}
Console.WriteLine("Reverse number={0}", reverse);
Console.ReadLine();
}
By this code I only get the numbers to reverse (13 -> 31)...
The input should contain a single line with an integer N, 1≤N≤1000000000 and I want my output in one line with one integer, the number I want to get by reversing the binary representation of N.
Something like that
// 13 = 1101b
int value = 13;
// 11 = 1011b
int result = Convert.ToInt32(new String(
Convert.ToString(value, 2)
.Reverse()
.ToArray()), 2);
Explanation:
Convert.ToString(value, 2) returns value in binary representation ("1101")
Reverse().ToArray() - reverse the string ('1','0','1','1') as sequence of characters and converts to array char[].
new String(...) constructs string "1011" from array of char
finally, Convert.ToInt32(..., 2) convert binary representation back to int
You can use Convert.ToString and Convert.ToInt32 methods, where 2 means binary:
int numb = int.Parse(Console.ReadLine());
var reversedString = Convert.ToString(numb, 2).ReverseString();
var result = Convert.ToInt32(reversedString, 2);
...
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
A fun excercise would be doing this without using the string conversion.
I have very little experience with bit twiddling so there is probably a faster and better way of doing this, but this seems to work:
public static IEnumerable<bool> ToBinary(this int n)
{
for (int i = 0; i < 32; i++)
{
yield return (n & (1 << i)) != 0;
}
}
public static int ToInt(this IEnumerable<bool> b)
{
var n = 0;
var counter = 0;
foreach (var i in b.Trim().Take(32))
{
n = n | (i ? 1 : 0) << counter;
counter++
}
return n;
}
private static IEnumerable<bool> Trim(this IEnumerable<bool> list)
{
bool trim = true;
foreach (var i in list)
{
if (i)
{
trim = false;
}
if (!trim)
{
yield return i;
}
}
}
And now you'd call it like this:
var reversed = n.ToBinary().Reverse().ToInt();