How can i convert my int array to string array in c#? - c#

I'm new in c# unity. I've to save my array of positions inside firebase for that I'm creating an int array like
int[] positions = new int[] {2, 4, 3};
its working fine but I don't know how can I convert this into string array like "[2, 4, 3]" to save in firebase.
I've searched on google and tried
string stringPositions = string.Join("", positions);
but it completely converts my array into a string like 234. And also how can I encode this string again into an array. Let me know if there is any other approach to do this. thanks!

First of all your question is wrong, you want to convert int array into string.
Use this:
int[] positions = new int[] {2, 4, 3};
string result = "[" + string.Join(",", positions) + "]";
Or this:
int[] positions = new int[] {2, 4, 3};
StringBuilder stb = new StringBuilder();
stb.Append("[");
stb.Append(string.Join(",", positions));
stb.Append("]");
string result = stb.ToString();
Or if you have C#6 or higher:
int[] positions = new int[] {2, 4, 3};
string result = $"[{string.Join(",", positions)}]";
Also if you want to convert back to your int array, for example you can just write your converter:
private int[] ConvertToIntArray(string myCustomString) //myCustomString is in "[1,2,3]" format
{
return myCustomString.Substring(1, myCustomString.Length - 2)
.Split(',')
.Select(s => int.Parse(s))
.ToArray();
}

"[1,2,3,4]"
is a json format of int array. Not string array.
You can use any JSON parser to do this.
I would recommend using JsonUtility which is built in Unity API.
Follow this guide to understand how it works:
Serialize and Deserialize Json and Json Array in Unity
Hope this helps.

Since you are new better use loop
int[] positions = new int[] {2, 4, 3};
string[] s = new string[positions.Length];
for (int x=0; x<positions.Length; i++)
s[x] = positions[x].ToString();

You have to do it manually.
String arrStr = "[";
for ( int i = 0; i < arr.length() - 1; i++) {
arrStr.join(arr[i]);
arrStr.join(",");
}
arrStr.join(arr[arr.length() - 1]);
arrStr.join("]");
Now you will have your array as you desired.

You have asked for a string array but your example is actually just a string that happens to look how you'd declare your int array in code.
For an actual array of strings you'd do what someone else has said and use linq
string[] stringArray = positions.select(p => p.ToString());
This would give you a new array who's item data type would be string .
If you want an actual string of text that looks like what you've asked for
string stringRepresentation = $"[{string.Join(", ", positions)}]";
Or with an old fashioned string format:
string stringRepresentation = string.Format("[{0}]", string.Join(", ", positions);
But just to be clear. This is isn't in depth stuff. Some quick googling and understanding of how to use the string.Join method would have brought you this answer.
So I'm going to l leave you with a pointer towards the trim method on a string and also the split method which should give you everything you need to recreate your int array

Related

Finding all possible combinations of int[] array, constrained by length in C#

int[] listOfValues = {1, 2, 5, 2, 6};
I need to be able to find all pair combinations of this array, including repetitions. Each value in the array comes from a deck of cards. So, if the value "2" appears twice in the array, for example, we can assume that these are two different values, and as such, need to be treated separately.
Sample of expected pairs of cards:
{1, 2}
{1, 2}
{2, 1}
{2, 1}
{2, 2}
{1, 5}
{1, 6}
etc.......
These separate int[] results will then need to be added to a List (if you can even add duplicate int[] values to a list, that is!), once all possible values have been found.
I have looked for a few hours online, and can't seem to get any of the solutions working for my particular task.
Does anyone have any ideas please?
You should really do homework on your own. Or at least try it first. You haven't provided code, so I cannot ethically give you the full solution.
However, this will get you started:
Think about it as if you were to do it by hand. Most people would pick the first value and the second value and write them down. Then they would write that pair backwards. Then they would do the first value and the third, then backwards, and so on and so on.
It would look something like:
{1,2}
{2,1}
{1,5}
{5,1}
{1,2}
{2,1}
{1,6}
{6,1}
{2,5} -Now we iterate again, starting with the second value
So how would we express that in code? Nested loops!
Here is the skeleton of an algorithm to solve your problem:
List<int[]> pairs = new List<int[]>();
for(int x = 0; x < listOfValues.Length - 1; x++)
{
for(int y = x+1; y < listOfValues.Length; y++)
{
// Create an array of the [x] position and [y] position of listOfValues
// Create another array, except swap the positions {[y],[x]}
// Add both arrays to the "pairs" List
}
}
Try to understand what this code is doing. Then fill in the blanks. You should get the correct answer. Always make sure to understand why, though. Also, try to see if you can figure out any improvements to this code.
With linq you could do it this way.
int[] listOfValues = { 1, 2, 5, 2, 6 };
var combination = listOfValues.Select(i => listOfValues.Select(i1 => new Tuple<int, int>(i, i1)).ToList())
.ToList()
.SelectMany(list => list.Select(x => x)).ToList();
With thanks to Clay07g's post, I was able to resolve the problem with the following code:
public static List<int[]> getCardCombos(int[] values)
{
List<int[]> pairs = new List<int[]>();
for (int x = 0; x < values.Length - 1; x++)
{
for (int y = x + 1; y < values.Length; y++)
{
int firstValue = values[x];
int secondValue = values[y];
// Create an array of the [x] position and [y] position of listOfValues
int[] xAndY = { firstValue, secondValue};
// Create another array, except swap the positions {[y],[x]}
int[] yAndX = { secondValue, firstValue };
pairs.Add(xAndY);
pairs.Add(yAndX);
// Add both arrays to the "pairs" List
}
}
return pairs;
}

How to generate a list of number in C#

How to create a list of num from 1 to 10
Example:
int[] values = Enumerable.Range(1,max).ToArray();
MessageBox.Show(values+",");
The output should be:
1,2,3,4,5,6,7,8,9,10
Please help
your code is generating array of integers from 1 to 10
int[] values = Enumerable.Range(1,10).ToArray();
but you're displaying them in wrong way (you're trying to cast int array to string), change it to
MessageBox.Show(string.Join(",", values);
string.Join will join your values separating them with ,
In .Net <4.0 you should use (and I believe OP is using one)
MessageBox.Show(string.Join(",", values.Select(x=>x.ToString()).ToArray());
Try like below using the generic version of Join<T>() method.
int[] arr = Enumerable.Range(1, 10).ToArray();
MessageBox.Show(string.Join<int>(",", arr));
Generate 1,2,3,4,5,6,7,8,9,10
(OR) using good old foreach loop
string str = string.Empty;
foreach (int i in arr)
{
str += i.ToString() + ",";
}
MessageBox.Show(str.TrimEnd(','));
List<int> values = Enumerable.Range(1, 10).ToList();
MessageBox.Show(string.Join(",", values.Select(x => x.ToString())));

Accessing arrays dynamically

I'm working on a project. I've a situation here. I'm having arrays with similar names consider arr1, arr2, arr3, etc.
Now I know the array number which I'm supposed to use let it be 2. Is there any way in c# to make the array name dynamically through strings and use it.
Like in flash action script we can do
_root["arr"+i][0]
here i contains the array number to be used.
No - you cannot access variable names dynamically. You can use reflection to dynamically access properties, but not variables. I would use a List<int[]> like so:
List<int[]> arrList = new List<int[]> {arr1, arr2, arr3);
int[] arr = arrList[i-1]; // since lists and arrays use 0-based indexes
You can use a dictionary:
var dictionary = new Dictionary<string, int[]>();
dictionary.Add("array1", arr1);
dictionary.Add("array2", arr2);
dictionary.Add("array3", arr3);
var arr = dictionary[string.Format("array{0}", i)];
What you want is something what JavaScript or dynamic languages have, but their array types are rather associative arrays. To reach the functionality you want you can use Dictionary:
var arr1 = new int[] { 0, 1, 2, 3 };
var arr2 = new int[] { 0, 1, 2, 3 };
var arr3 = new int[] { 0, 1, 2, 3 };
var _root = new Dictionary<string, int[]>();
_root.Add("arr1", arr1);
_root.Add("arr2", arr2);
_root.Add("arr3", arr3);
for (int i = 1; i <= 3; i++)
{
int arrElem = _root["arr" + i][0];
}
Note the expression within the for loop, it's like what you were asking for.
use list for performing dynamic operations
As suggested in other answers the way to achieve the dynamism you're looking for is to put all of the arrays in a collection ( List<int[]> ) and then you can write more generalized code which operates on the contents of a given array without knowing which array it's operating on at compile time.

c# Leaner way of initializing int array

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?
int nums=5;
int[] array= new int[nums];
for(int i=0;i<num;i++)
{
array[i] = i;
}
Maybe with linq or some array.function?
int[] array = Enumerable.Range(0, nums).ToArray();
Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;
int[] array = Enumerable.Range(0, nums).ToArray();
Generates a sequence of integral numbers within a specified range.
Using Enumerable.Range
int[] array = Enumerable.Range(0, nums).ToArray();
Maybe I'm missing something here, but here is the best way I know of:
int[] data = new int [] { 383, 484, 392, 975, 321 };
from MSDN
even simpler:
int[] data = { 383, 484, 392, 975, 321 };

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