Fill a string[] array using split - c#

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);

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;

Convert Ienumerable<int> to array and add to list C#

I have a simple code:
List<int[]> list = new List<int[]>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
var v = vec.ToArray();
list.Add(v);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, list);
MessageBox.Show(toDisplay);
This is vector:
int[] vector = new int[length];
Random z = new Random();
for (int i = 0; i < length; i++)
{
vector[i] = z.Next(-100, 100);
}
What I want to do is to slice my vector on smaller vectors and add them to list of int. Using my code I only get System.Int32[] in MessageBox. I know that maybe my code it's not the right way. I barely know C#.
How can I do this in other way?
Apparently you mean to slice the initial array into smaller chunks and display them in a single line. This can be done using Linq as follows.
var StringToDisplay
= String.Join(Environment.NewLine, list.Select(iList => String.Join(",", iList)));
List<int[]> list is a list of arrays, not numbers. Calling ToString() on an array uses Object.ToString() which returns the object's (array's) type.
If you want to display a list of pages, you should change your string construction code to work with the inner arrays. One option is to use LINQ :
var lines=from page in list
select string.Join(",", page);
string toDisplay = string.Join(Environment.NewLine, lines);
It's better to use StringBuilder though, to avoid generating a lot of temporary strings:
var builder=new StringBuilder();
foreach(var page in list)
{
builder.AppendLine(string.Join(",", page));
}
string toDisplay = builder.ToString();
If you want a list of numbers change the list type to List. You can also simplify the code by using AddRange, eg :
List<int> list = new List<int>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
list.AddRange(vec);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, lines);

Write list to csv file c#

Imagine i have 2 lists filled with values. I want all the elements from the first list, written into the first column, all the elements from the second list written into the second column and so on.
If both list have the same size, this works fine:
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
sw.Write(newLine);
}
My problem is that if the lists have different sizes, code fails with out of range exception obviously. I tried adding ',' between columns but it's not working.
Instead of ElementAt you should use ElementAtOrDefault :
According to msdn it
Returns the element at a specified index in a sequence or a default
value if the index is out of range.
try this :
List<int?> valueArray = new List<int?>();
List<int?> secondValueArray = new List<int?>();
//... fill lists
valueArray.Add( 1 );
valueArray.Add(2);
valueArray.Add(3);
secondValueArray.Add( 4 );
while (valueArray.Count > secondValueArray.Count)
secondValueArray.Add(null);
while (secondValueArray.Count > valueArray.Count)
valueArray.Add(null);
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
Console.WriteLine(newLine);
}
;
Result :
1,4
2,
3,
As mentioned before, use ElementAtOrDefault(). And check which array is the longest one. Furthermore, you might want to write an empty string instead of NULL if there's no value.
int count = Math.Max(firstArray.Count(), secondArray.Count());
for (int i = 0; i < count; i++)
{
var value1 = firstArray.ElementAtOrDefault(i) ?? String.Empty;
var value2 = secondArray.ElementAtOrDefault(i) ?? String.Empty;
var newLine = string.Format("{0},{1}", value1, value2);
sw.Write(newLine);
}

c# copyto arrays in params

I have made a function that can extend an arrays value by 1 but
I have an issue where I tried to make the following function:
//This is error free and compiles properly
public string[] addindex(string[] Input)
{
string[] ar2 = new string[Input.Length + 1];
Input.CopyTo(ar2, 0);
ar2.SetValue("", Input.Length);
Input = ar2;
return Input;
}
support more than 1 parameter.
So, I made this:
public string[] addindexes(params string[] lists)
{
string[] ar2;
for (int x = 0; x < lists.Length; x++)
{
ar2 = new string[lists[x].Length + 1];
lists[x].CopyTo(ar2, 0); //Error here
ar2.SetValue("", lists[x].Length);
lists[x] = ar2; //Error here
}
return lists;
}
It seems like I'm using wrong syntax or something?
You need to change params string[] lists to params string[][] lists as you're now passing in an array of arrays. (At least, the method sees an array of arrays, even if you pass in multiple separate arrays.)
Similarly you need to change the return type to string[][].
See this for more information.
You can use Resize method for simpler:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
To extend one more item:
Array.Resize(ref list, list.Length + 1);
list[list.Length - 1] = string.Empty;
To extend more than one 1:
int size = 5;
Array.Resize(ref list, list.Length + size);
for (int i = list.Length - size; i < list.Length; i++)
list[i] = string.Empty;
How about you just use generic list in the first place?
List<string> Input = new List<string>();
Input.Add("new item");

Adding elements to a C# array

I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.
The obvious suggestion would be to use a List<string> instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.
Of course, I want to make things more interesting (my day that is), so I will answer your question directly.
Here are a couple of functions that will Add and Remove elements from a string[]...
string[] Add(string[] array, string newValue){
int newLength = array.Length + 1;
string[] result = new string[newLength];
for(int i = 0; i < array.Length; i++)
result[i] = array[i];
result[newLength -1] = newValue;
return result;
}
string[] RemoveAt(string[] array, int index){
int newLength = array.Length - 1;
if(newLength < 1)
{
return array;//probably want to do some better logic for removing the last element
}
//this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way
string[] result = new string[newLength];
int newCounter = 0;
for(int i = 0; i < array.Length; i++)
{
if(i == index)//it is assumed at this point i will match index once only
{
continue;
}
result[newCounter] = array[i];
newCounter++;
}
return result;
}
If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:
var oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0
Don't use an array - use a generic List<T> which allows you to add items dynamically.
If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.
Since arrays implement IEnumerable<T> you can use Concat:
string[] strArr = { "foo", "bar" };
strArr = strArr.Concat(new string[] { "something", "new" });
Or what would be more appropriate would be to use a collection type that supports inline manipulation.
Use List<string> instead of string[].
List allows you to add and remove items with good performance.
What's abaut this one:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
One liner:
string[] items = new string[] { "a", "b" };
// this adds "c" to the string array:
items = new List<string>(items) { "c" }.ToArray();
You should take a look at the List object. Lists tend to be better at changing dynamically like you want. Arrays not so much...
You can use a generic collection, like List<>
List<string> list = new List<string>();
// add
list.Add("element");
// remove
list.Remove("element");
You can use this snippet:
static void Main(string[] args)
{
Console.WriteLine("Enter number:");
int fnum = 0;
bool chek = Int32.TryParse(Console.ReadLine(),out fnum);
Console.WriteLine("Enter number:");
int snum = 0;
chek = Int32.TryParse(Console.ReadLine(),out snum);
Console.WriteLine("Enter number:");
int thnum = 0;
chek = Int32.TryParse(Console.ReadLine(),out thnum);
int[] arr = AddToArr(fnum,snum,thnum);
IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
{
return s;
});
Console.WriteLine("Here your result:");
oarr.ToList().FindAll(delegate(int num) {
Console.WriteLine(num);
return num > 0;
});
}
public static int[] AddToArr(params int[] arr) {
return arr;
}
I hope this will help to you, just change the type

Categories