string of integers to int[] array C# [duplicate] - c#

This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 4 years ago.
This question is different as it tackles the issue of converting a char to an int when adding to an integer array.
The following piece of code, I am trying to implement a string of integers into a int[] array in C#.
My desired output is an array of:
12345678910
This is my code, however, the output of this is not what I desire:
string numbers = "12345678910";
int[] array = new int[numbers.Length];
for (int i = 1; i <= numbers.Length; i++)
{
array[i - 1] = numbers[i-1];
}
foreach(var y in array)
{
Console.Write(y);
}
Output of given code:
4950515253545556574948
Can somebode tell me why I am getting this output, and what I can do to fix this? Thank you!
Edit: Changed my code and it works using this:
for (int i = 0; i < numbers.Length; i++)
{
array[i] = int.Parse(numbers[i].ToString());
}

First of all, I don't think you'll be able to distinguish a two digit number using this method.
I refer to this part of your code: string numbers = "12345678910";
Iterate through your string characters and parse to Int (if that's what's required) (credit) (credit)
foreach (char character in yourString)
{
int x = (int)Char.GetNumericValue(character);
//code to add to your array of ints
}

Related

How to solve Cannot convert type 'int' to 'int[]' error? [duplicate]

This question already has answers here:
Iterate Multi-Dimensional Array with Nested Foreach Statement
(12 answers)
Closed 2 years ago.
I'm starting my own question because I can't find anything directly related to c# and the solution I am using is different approach.
The question is described as follows
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange.
If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2.
I currently have the following as my code:
public class Solution {
public int OrangesRotting(int[][] grid) {
var rows = grid.Length;
var cols = grid[0].Length;
HashSet<string> fresh = new HashSet<string>();
HashSet<string> rotten = new HashSet<string>();
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
var current = grid[i][j];
if(current == 1){
fresh.Add(""+i+j);
} else if (current == 2){
rotten.Add(""+i+j);
}
}
}
int minutes = 0;
int[,] directions = {{0,1},{1,0},{-1,0},{0,-1}};
while(fresh.Count > 0){
HashSet<string> infected = new HashSet<string>();
foreach(string s in rotten){
int i = s[0] - '0';
int j = s[1] - '0';
foreach(int[] direction in directions){
int nextI = i + direction[0];
int nextJ = j + direction[1];
if(fresh.Contains(""+nextI+nextJ)){
fresh.Remove(""+nextI+nextJ);
infected.Add(""+nextI+nextJ);
}
}
}
if(infected.Count == 0) return -1;
minutes++;
}
return minutes;
}
}
The issue I am having is I get the following compile error:
Line 29: Char 17: error CS0030: Cannot convert type 'int' to 'int[]' (in Solution.cs)
The array declaration int[,] directions defines a multidimensional array, which, strangely enough, is not an IEnumerable in C#. This means quite a few items that a "normal" array supports aren't available; one of them is a foreach iteration through the top-level array, which would make intuitive sense to write. Instead, what you're iterating through is a single-dimension representation of your multidimensional array - not what you want.
You can do one of two things: either use a jagged array instead - int[][] directions - or switch to a nested for loop instead, accessing each element of the array in the inner loop.

nested loop with array c# [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I have the following array:
public int[] ID = {0,1,2,3,4};
I´m calling the following method, which contains an get-method in an framework:
int[] marker = this.m_TuioManager.getID(this.ID);
Get-Method in the framwork class:
public int[] getID(int[] wert)
{
int number= 4;
for (int i = 0; i<=number; i++)
{
for (int j = 0; j<=number; j++)
{
wert[i] = wert[j];
}
}
return wert;
}
The exception is:
Array index out of range
which I don´t understand. Cauze my array has 5 numbers from 0 to 4. And in the for loop I´m iterating until 4.
What I want later, is to compare the values in the array like wert[0] = 0, wert[1] = 1 and so on(until 4),with an other variable.
If you want to avoid "Array index out of bounds" errors, don't write code that assumes arrays always have X number of elements. Either check the .Length of the array before you attempt to access 4 elements of it, or write a loop that runs to the array.Length rather than always running to a fixed 4 elements
if(array.Length < 4)
throw new Exception("min array length is 4, you passed " + array.Length);
Or
for(int i = 0; i < array.Length; i++)
Or
foreach(int i in array)
If you can get any of these lines of code to crash with an AIOOB exception, inform Microsoft

PadRight in string of arrays doesn't add chars

I created array of strings which includes strings with Length from 4 to 6. I am trying to PadRight 0's to get length for every element in array to 6.
string[] array1 =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i <= array1.Length-1; i++)
{
if (array1[i].Length < 6)
{
for (var j = array1[i].Length; j <= 6; j++)
{
array1[i] = array1[i].PadRight(6 - array1[i].Length, '0');
}
}
Console.WriteLine(array1[i]);
}
Right now the program writes down the exact same strings I have in array without adding 0's at the end. I made a little research and found some informations about that strings are immutable, but still there are some example with changing strings inside, but I couldn't find any with PadRight or PadLeft and I fell like there must be a way to do it, but I just can't figure it out.
Any ideas on how to fix that issue?
The first argument to PadRight is the total length you want. You've specified 6 - array1[i].Length - and as all your strings start off with at least 3 characters, you're padding to at most 3 characters, so it's not doing anything.
You don't need your inner loop, and your outer loop condition is more conventionally written as <. This is one way I'd write that code:
using System;
public class Test
{
static void Main()
{
string[] array =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i < array.Length; i++)
{
array[i] = array[i].PadRight(6, '0');
Console.WriteLine(array[i]);
}
}
}
In fact I'd probably use foreach, or even Select, but that's a different matter. I've left this using an array to be a bit closer to your original code.

Iterate two Arrays with ForEach statement in C# [duplicate]

This question already has answers here:
Iterate two Lists or Arrays with one ForEach statement in C#
(12 answers)
Closed 8 years ago.
I have 2 array
string[] Namesvalues = Names.Split(',');
string[] TotalValues = Total.Split(',');
Above both arrays have exactly equal values.what i want to do is to iterate above two arrays in parallel and want to get one by one value from both arrays.
Can any one tell me how can i do that??
You could simply use a for-loop:
for(int i = 0; i < NamesValues.Length; i++)
{
string name = NamesValues[i];
string totalValue = TotalValues[i];
}
If the length is different you could use ElementAtOrDefault:
for(int i = 0; i < Math.Max(NamesValues.Length, TotalValues.Length) ; i++)
{
string name = NamesValues.ElementAtOrDefault(i);
string totalValue = TotalValues.ElementAtOrDefault(i);
}
You also could use Enumerable.Zip to create an anonymous type with both values:
var namesAndValues = NamesValues.Zip(TotalValues,
(n, tv) => new { Name = n, TotalValue = tv });
foreach(var nv in namesAndValues)
{
Console.WriteLine("Name: {0} Value: {1}", nv.Name + nv.TotalValue);
}
Note that the second approach using a for-loop and ElementAtOrDefault is different to to the Enumerable.Zip approach.
The former iterates both arrays completely and ElementAtOrDefault returns null for the value of the smaller array if there is no element at that index.
The latter Zip combines elements only until it reaches the end of one of the sequences.
So when you use Math.Min instead of Math.Max in the for-loop you get a similar behaviour, but then you should use the first approach anyway since there's no need for ElementAtOrDefault.
//exactly equal length
for (int i = 0; i < Namesvalues.Length; i++)
{
var name = Namesvalues[i];
var total = TotalValues[i];
}

How to split a number into individual digits in c#? [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

Categories