Array.Copy and accessing string array with variable - c#

I've tried several things and just cannot seem to get this. I have 10 MotorReply strings that I then split into array elements. Then I want to copy those elements to another array so I can loop through again but whatever I try, I can't access the BayReplyArray by using the incrementing i variable, i.e. BayReplyArray[i]
Declarations:
string[] MotorReplyArray = new string[30];
string[] BayReplyArray1 = new string[30];
string[] BayReplyArray2 = new string[30];
string[] BayReplyArray3 = new string[30];
up to 10
int j = 0;
for (int i = 1; i < 11; i++)
{
// here we take the Motor? reply string for each bay and split the parameters into individual string arrays
char[] delimiters = new char[] { '\r', ':' };
MotorReplyArray = MotorReply[i].Split(delimiters);
foreach (string line in MotorReplyArray)
{
// trim whitespace from ends
MotorReplyArray[j] = line.Trim();
j++;
}
Array.Copy(MotorReplyArray, BayReplyArray[i], j);
Array.Clear(MotorReplyArray, 0, j);
j = 0;
}

I can't access the BayReplyArray by using the incrementing i variable, i.e. BayReplyArray[i]
You seem to think that if i is 1 then BayReplyArray[i] is the same as BayReplyArray1, which is not the case. You can easily enough change to a jagged array:
string[] MotorReplyArray = new string[30];
string[][] BayReplyArray = new string[][10];
now BayReplyArray[i] is a string array and you can use Array.Copy on it.

Related

How to randomize the word that been get on the textfile

I want to ask if how can I randomize a word that I've get from the textfile data I made.
I already have the word actually from the textfile and stored into an array of character.
Here's what I have so far
I created a method called Shuffle
void Shuffle(string[] chArr)
{
//Shuffle
for (int i = 0; i < chArr.Length; i++)
{
string tmp = chArr[i].ToString();
int r = Random.Range(i, chArr.Length);
chArr[i] = chArr[r];
chArr[r] = tmp;
}
Debug.Log(chArr);
}
and use it like this
string temp = textArray[rowsToReadFrom[0]];
temp = System.Text.RegularExpressions.Regex.Replace(temp, #"\s", "");
char[] chArr = temp.ToCharArray();
string s = chArr.ToString();
string[] ss = new string[] { s };
Shuffle(ss);
foreach (char c in chArr)
{
testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
clone.transform.SetParent(container);
charObjects.Add(clone.Init(c));
//Debug.Log(c);
}
It still doesn't randomize that word I get from the textfile data.
EDITTED
So far here's what I did
string temp = textArray[rowsToReadFrom[0]];
temp = System.Text.RegularExpressions.Regex.Replace(temp, #"\s", "");
char[] chArr = temp.ToCharArray();
string charResult = "";
for(int i = 0; i < chArr.Length; i++)
{
int ran = Random.Range(0, chArr.Length);
charResult += chArr[ran];
}
Debug.Log(charResult);
foreach (char c in charResult)
{
testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
clone.transform.SetParent(container);
charObjects.Add(clone.Init(c));
//Debug.Log(c);
}
But instead of giving me for example the word "Abandon" it would give me sometimes a randomize word "aaaabn" could someone help me out why?
I will be using Fisher–Yates_shuffle
public static string Shuffle(string str)
{
System.Random random = new System.Random();
var array = str.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(i, array.Length);
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return String.Join("", array);
}
and to use it simply do
var f = "hello";
Console.WriteLine(Shuffle(f));
Your code is just getting random letters from that word but does not exclude duplicate. What you want instead is randomize the array of chars and convert it back to a string
System.Random rnd = new System.Random();
Char[] randomCharArray = chArr.OrderBy(x => rnd.Next()).ToArray();
string charResult = randomCharArray.ToString();
Unity has its own implementation of Random so be sure you use System.Random
it's most easier if you use a list (let call it initial list), (it may have some performance overheat do to shifts on remove, but i'm wonder if using a linked list would solve that...
Here what you can do if you do as i said:
Fill the list, with your words, or char, or any data which you want to randomize
Create another list or array to store randomized data in (result)
create a while loop, and check while, your initial list Has Item (count > 0)
use Random, and performe rand.Next(0, initialList.Count)
take the item within the index of random number and append it to the result list, (or replace free slot if you are using array)
List<string> initial = new List<string>();
initial.AddRange(data);
Random rand = new Random();
List<string> result = new List<string>();
while (initial.Count > 0) // LINQ: initial.Any()
{
int index = rand.Next(0, initial.Count);
result.Add(initial[index]);
initial.RemoveAt(index);
}
return result;

How can I use Empty literal on Split('')

I need to read a string with non-space separated values (0-9).
Why can't I use Empty literal in String.Split method?
// Reading Grid's row and col size
gridInputValues = Console.ReadLine().Split(' ');
gridRow = int.Parse(gridInputValues[0]);
gridCol = int.Parse(gridInputValues[1]);
gridMatrix2D = new int[gridRow, gridCol];
// Reading Grid's row * col matrix values
for( int r = 0; r < gridRow; r++ )
{
//string[] inputVal = Console.ReadLine().Split('');
//string[] inputVal = Console.ReadLine().Split(string.Empty));
string inputVal = Console.ReadLine();
for( int c = 0; c < gridCol; c++ )
{
//gridMatrix2D[r, c] = int.Parse(inputVal[c]);
gridMatrix2D[r, c] = int.Parse(inputVal[c].ToString());
}
Why not,
string[] inputVal = Console.ReadLine().Split('');
or
string[] inputVal = Console.ReadLine().Split(string.Empty));
works?
Alternatively,
Is using string.ToString good practice in such case?
or
Will the string.ToString method on each iteration increase the running time?
EDIT 1:
Input:
"12345" // type is string
Expected Output:
"1","2","3","4","5" // type is string[]
What about:
Console.ReadLine().ToArray()
You don´t seem to need split the string, you just want the individual characters.
or String.ToCharArray as #Tim Schmelter correctly pointed out.
You can probably try this
string[] inputVal = Console.ReadLine().Split(null);
or
string[] inputVal = Console.ReadLine().Split(new char[0], StringSplitOptions.RemoveEmptyEntries)
You can instead use chars:
int[] intArray = inputVal.Select(ch => ch-'0').ToArray();

Index was outside the bounds of the array while copying value in a string array

When I run the code, it says that "Index was outside the bounds of the array."
string xyz ="";abc: 123 ;234 ;345 ;def: 234 ;456 ;xyz: 123;"";
string[] lines1 = abc.Split(':');
string[] buffer1 = new string[]{};
for (int i = 0; i < lines1.Length; i++)
{
//string[] lines2 = lines1[i].Split(';');
string[] lines2 = lines1[i].Split(new char[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < lines2.Length; j++)
{
buffer1[j] = lines2[j];
}
}
In the buffer1[j] = lines2[j], I am copying the value of each lines2 in buffer1 which I need to use after the second loop. But I am getting that exception in that line when I run the code.
buffer1 is an array, which means that it's of a fixed sized and can't grow to hold what you're trying to put in it. If you try to access buffer1[16] and buffer1 isn't large enough for that, it will throw the exception you're seeing.
Instead of an array, try using a List<int>:
var buffer1 = new List<int>();
foreach (string item in lines1)
{
buffer1.AddRange(item.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
This will allow you to add as many items to buffer1 as you want.

Fill a string[] array using split

I have the following text
part1:part2
and the following string[] array
string[] tmp = new string[3];
how can i split my text and put it into the array so the array looks like this:
{"part1", "part2", ""}
I tried using the .split(':'); but that just reassigns the array and so it has only 2 elements instead of 3
thanks
Although I am sure that there is a better way to do what you are trying to do, in my opinion the easiest way to achieve precisely the result you are after is to do a copy:
var input = "text1:text2";
var temp = new [] {"", "", ""};
var split = input.Split(':');
Array.Copy(split, temp, split.Length <= 3 ? split.Length : 3);
not overly elegant, but if it's what you want, you can Resize the array.
string input=#"part1:part2";
var result = input.Split(':');
Array.Resize(ref result, 3);
result[2]=string.Empty;
If you really need three elements in the resulting array, you will have to copy the result from string.Split to the final array, e.g. by using a simple loop:
var result = new string[3];
var split = "part1:part2".Split(":");
for(var i = 0; i < result.Length; ++i)
{
if(i < split.Length)
result[i] = split[i];
else
result[i] = string.Empty;
}
var str = "part1:part2";
var result = new string[3];
result = (str + "".PadLeft(result.Length - str.Count(c=>c==':') - 1,':')).Split(':');
private static string[] ProcessInput(string input, int length)
{
// handle empty or null input
if (string.IsNullOrEmpty(input))
return null;
var items = input.Split(':').ToList();
// adding empty strings untill given length
while (items.Count <= length)
{
items.Add(string.Empty);
}
//even split return more items than length return expected length
return items.Take(length).ToArray();
}
call the method as
var result = ProcessInput("text1:text2:text4:text5", 3);

How do I create a string from one row of a two dimensional rectangular character array in C#?

I have a 2 dimensional array, like so:
char[,] str = new char[2,50];
Now, after I've stored contents in both str[0] and str[1], how do I store it in a
string[] s = new string[2];
?
I tried
s[0] = str[0].ToString();
but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?
A jagged array is almost always the best solution for a variety of reasons, and this is one good example. There is so much more flexibility available with an array of arrays than with a multi-dimensional array. In this case, once you have the values in an array of chars, then a constructor on the string class can be used to create a string from it.
Also, the jagged array would be composed of "vectors" (i.e., a single-dimensional arrays with a zero-lower-bound index), which are much more preferment in .Net because they are given special treatment by the CLR.
So without knowing what the rest of your program is doing, that would be my recommendation.
If you do attempt to construct a string manually by looping through the array indexes, instead of using a jagged array, then I recommend using the StringBuilder class to do it.
I just banged this out, but it should be something like this:
// For the multi-dimentional array
StringBuilder sb = new StringBuilder();
for (int stringIndex = 0; stringIndex < s.Length; stringIndex++)
{
sb.Clear();
for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)
sb.Append(str[stringIndex,charIndex]);
s[stringIndex] = sb.ToString();
}
// For the jagged array
for (int index = 0; index < s.Length; index++)
s[index] = new string(str[index]);
Assuming the dimensions are fixed as 2x50:
char[,] str = new char[2,50];
// populate str somehow
// chose which of the strings we want (the 'row' index)
int strIndex = 0;
// create a temporary array (faster and less wasteful than using a StringBuilder)
char[] chars = new chars[50];
for (int i = 0; i < 50; i++)
chars[i] = str[strIndex, i];
string s = new string[chars];
This would be easier and more performant if you used a jagged array:
char[][] str = new char[2][];
Then you could write:
string s = new string(characters[0]);
I would agree with using a jagged array. You can use this helper method to initialize a jagged array:
static T[][] InitJaggedArray<T>(int dimension1, int dimension2)
{
T[][] array = new T[dimension1][];
for (int i = 0; i < dimension1; i += 1)
{
array[i] = new T[dimension2];
}
return array;
}
So
char[,] str = new char[2,50];
would become
char[][] str = ArrayHelper.InitJaggedArray<char>(2, 50);
You would then access elements in it like so
str[0, 10] = 'a';
And to make it a string you would do
string s = new string(str[0]);
You can do it with LINQ:
string[] Convert(char[,] chars)
{
return Enumerable.Range(0, chars.GetLength(1))
.Select(i => Enumerable.Range(0, chars.GetLength(0))
.Select(j => chars[j, i]))
.Select(chars => new string(chars.ToArray());
}

Categories