Issue splitting ListBox line back into 3 values - c#

I had three values (Name, Course and Average) which were assigned to 3 arrays. I had to combine them and put them in a listbox. Now, I need to be able to select the same line and break it back up into the 3 variables.
My listbox output looks like this:
Lastname, firstname SEC360 93.5
I tried to do a split with space, but that breaks up my lastname and firstname, which need to be one combined variable with the comma included (I need to check it against the array in which it is placed). I cannot do substring either, because I do not have a set value. Any ideas?
EDIT:
I am sorry everyone. Im a inexperienced programmer (to say the least) and new to this site.
This is where I loaded the arrays:
studentNamesAr[studentCount] = studentNameTxtBox.Text;
courseAr[studentCount] = courseNumTxtBox.Text;
gradesAr[studentCount, 0] = Convert.ToInt32(grade1TxtBox.Text);
gradesAr[studentCount, 1] = Convert.ToInt32(grade2TxtBox.Text);
gradesAr[studentCount, 2] = Convert.ToInt32(grade3TxtBox.Text);
gradesAr[studentCount, 3] = Convert.ToInt32(grade4TxtBox.Text);
This is where I load the arrays to the listbox:
for (int i = 0; i != studentCount; i++)
{
studentAvg = ((gradesAr[i, 0] + gradesAr[i, 1] + gradesAr[i, 2] + gradesAr[i, 3]) / 4);
studentListBox.Items.Add(string.Format("{0, -20} {1, 20} {2, 20:F1}", studentNamesAr[i], courseAr[i], studentAvg));
}
Yes this is Windows Forms.
Data is not lost in arrays. When the program runs I should have maybe 5 entries. I need to split them back up so that when I select one from the listbox (to delete it), I will find the values in the 3 arrays and delete them, and then shift the remaining array values up.

If you preserve the order of your items in the listbox, the SelectedIndex of the listbox should match up with the indices from your original arrays. So once you have that, you can go about shifting your arrays up (which is pretty tedious).
For the record, there are much better constructs to use to approach this problem, but I'm assuming the stipulation of using arrays is part of a homework assignment. :)

You could hold the value separated by some other delimiter in the .Tag property.

I suggest you to replace the ", " (notice the space after the ',') with something else (like ";") then use the split method with space as the parameter.
string s = "Lastname, firstname SEC360 93.5";
string[] result = s.Replace(", ", ";").Split(' ');
then you may change back the result[0] by replacing ";" with ", "

Related

unity C# line Renderer array of lines

i want to make many lines use line renderer and i need double array. One of them is number of lines, and other one is data of points position.
...
positions[n + 1] = new Vector3(positions[n].x + Bxpe, positions[n].y + Bype, positions[n].z + Bzpe);
linerenderer.SetPositions(positions);
...
it work when number of line is one but
...
positions[z,n + 1] = new Vector3(positions[n].x + Bxpe, positions[n].y + Bype, positions[n].z + Bzpe);
linerenderer[1].SetPositions(positions[???]);
...
when i want to make like this, i dont know how write it right way.
pleace help
If you really want to keep using a 2d-array checkout how to "slice" arrays out of it
However, in your case instead of a 2-dimensional array
Vector3[,]
I would rather simply use a jagged array
Vector3[][]
and then do e.g.
positions[z][n + 1] = positions[z][n] + new Vector3(Bxpe, Bype, Bzpe);
...
linerenderer[z].SetPositions(positions[z]);

Removing duplicate items from list, ignoring spaces

I want to remove duplicate items from an array, ignoring spaces, so Distinct.ToArray() won't work.
I copied the array to a list and enumerate backwards through the array with a nested loop. I compare the array item of the inner loop with that of the outer loop. The loop runs without problems, but when I remove an item from the copied list that is indexed to the inner loop, I get an exception.
for (int k = aArray.Length - 1; k > 0 ; k--)
{
for ( int j = k -1; j >= 0; j--)
{
if (Regex.Replace(aArray[k], #"\s", "") ==
Regex.Replace(aArray[j], #"\s", ""))
{
aList.RemoveAt(j);
}
}
}
How can I enumerate through an array and remove items from a copy of that array based on a comparison of items in the array? Thanks.
Edit: Given three strings, one containing NOSPACE, one containing NO SPACE (1 sp), and one containing NO SPACE (2 sp), but otherwise the same, I want to remove two of those strings. Doesn't matter which two. Distinct won't work because it doesn't ignore spaces, and the suggested answer removes all spaces.
2nd edit: Greg's answer does work, but I can't upvote it (less than 15). I've been struggling with this all day....
3rd edit: Greg's answer works, but removes all spaces in strings. I want to remove items that are identical except for spaces, and leave spaces in items. I still think that enumeration should work, somehow.
Try this:
var result = aArray.Select(x => x.Replace(" ", string.Empty)).Distinct();
you can use Regex.Replace(x, #"\s", "") instead of x.Replace if you want to
var array = new[] { " 1 2 ", " 12 ", "1 ", " 1", "12", " 1 ", "3 3", " 33" };
var result = array
.ToLookup(k => k.Replace(" ", string.Empty))
.Select(v => v.First())
.ToArray();

Add string to array

I am trying to add a string to an array, I have done a lot of research, and came up with two options but neither work, I get a pop-up and the details make it sound like my array is out of bounds, Both methods are inside my addSpam function. Any ideas on how to fix either method?
namespace HW8_DR
{
class Tester : Spam_Scanner
{
private string[] spam = {"$$$", "Affordable", "Bargain", "Beneficiary", "Best price", "Big bucks",
"Cash", "Cash bonus", "Cashcashcash", "Cents on the dollar", "Cheap", "Check",
"Claims", "Collect", "Compare rates", "Cost", "Credit", "Credit bureaus",
"Discount", "Earn", "Easy terms", "F r e e", "Fast cash", "For just $XXX",
"Hidden assets", "hidden charges", "Income", "Incredible deal", "Insurance",
"Investment", "Loans", "Lowest price", "Million dollars", "Money", "Money back",
"Mortgage", "Mortgage rates", "No cost", "No fees", "One hundred percent free",
"Only $", "Pennies a day", "Price", "Profits", "Pure profit", "Quote", "Refinance",
"Save $", "Save big money", "Save up to", "Serious cash", "Subject to credit",
"They keep your money – no refund!", "Unsecured credit", "Unsecured debt",
"US dollars", "Why pay more?"};
public static double countSpam = 0;
public static double wordCount = 0;
public static string posSpam = "";
public void tester(string email)
{
for(int i = 0; i < spam.Length-1; i++)
if(email.Contains(spam[i]))
{
countSpam++;
posSpam = string.Concat(posSpam, spam[i], "\r\n\r\n");
}
wordCount = email.Split(' ').Length;
}
public void addSpam(string spamFlag)
{
//attempt 1 to add string to spam array
Array.Resize(ref spam, spam.Length + 1);
spam[spam.Length] = spamFlag;
//attempt 2 to add string to spam array
string[] temp = new string[spam.Length + 1];
Array.Copy(spam, temp, spam.Length);
temp.SetValue(spamFlag, spam.Length);
Array.Copy(temp, spam, temp.Length);
}
}
}`
Simple solution: don't use an array! List<T> is much better suited for this.
using System.Collections.Generic;
...
private List<string> spam = {"$$$", "Affordable", "Bargain", "Beneficiary", ... }
...
public void addSpam(string spamFlag)
{
spam.Add(spamFlag);
}
DLeh's answer is best - this is what a List<T> is for, so that's your solution.
But the reason things are failing for you is that you're attempting to access an index that is one higher than the max index of the array. The highest index is always one less than the length, because arrays are zero-based.
int[] arr = new[] { 1, 2, 3 };
Console.WriteLine(arr.Length); // 3
Console.WriteLine(arr[0]); // 1
Console.WriteLine(arr[1]); // 2
Console.WriteLine(arr[2]); // 3
Console.WriteLine(arr[3]); // Exception
To access the last item in an array, you either need to use:
var lastItem = arr[arr.Length - 1];
// or
var lastItem = arr[arr.GetUpperBound(0)];
Array.Resize(ref spam, spam.Length + 1);
spam[spam.Length] = spamFlag;
Here you're trying to write to index 58 (spam.Length after the re-size) of a 58-element zero-indexed array; that is, it goes from 0 to 57.
You should use:
Array.Resize(ref spam, spam.Length + 1);
spam[spam.Length - 1] = spamFlag;
That said, you should really use List<string> instead. Among other things it does the resizing of the internal array it uses in batches rather than on every Add(), which makes things much more efficient, as well as being easier.
If you really need an array for some reason, then use List<string> for most of the work, and then call ToArray() at the end.
While DLeh raise legit points about how it's better to use a List that dynamically grows, and Joe's answer provides a great explanation, I want to add on to a few more things.
Firstly, to Answer your question, to fix either method, you probably wanted to do spam[spam.Length-1] = spamFlag instead of spam[spam.Length] = spamFlag in attempt one. Because indexes start at 0 and the last index within the bound is thus length -1 (As Joe pointed out)
Your second attempt will not work as an exception is thrown if either array is too short. See this dotnetPerl link on the explanation. Basically it isn't recommended to use Array.Copy as you have to ensure the types and lengths are the same as well.
To elaborate on Array.Resize(), it should be noted that it's actually a misnomer in which C# doesn't actually resize the array. Rather, it creates a new array and copies the contents over. It always does this unless an exception is thrown, so from a performance point of view this is discouraged. (You could have a variable to keep track of how full your array is, and always grow it by double the amount, this avoids you from having to always create a new array.)
This is also used in hashtables as well where if a certain bucket is full, we grow it and rehash everything back in (it's a really fast lookup table/data structure).
Read this DotNetPerl tutorial on Array Resize
However, a lot of times a List is better, but of course there may be a reason why you don't want to/can't use. I know of a few classes that explicitly tell us not to use built in data structures to learn how arrays work.

How do I assign values to items in the list box in c#?

I have a List Box with different Cakes in them. How do I give each cake a price and have my label display the total cost of the selected cakes? The following is the code I have so far.
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
}
double tax = 1.13;
lblOrdered.Text = "You have ordered: " + strCakes + '\n' + "Total Cost: " + (tax * cakeCost).ToString("C");
I tried using switch like the following but that only shows the cost of the last selected item.
switch (lstCakes.SelectedIndex)
{
case 0:
if (lstCakes.SelectedIndex == 0)
{
cakeCost = 18;
}
break;
case 1:
if (lstCakes.SelectedIndex == 1)
{
cakeCost = 25;
}
break;
case 2:
if (lstCakes.SelectedIndex == 2)
{
cakeCost = 40;
}
break;
case 3:
if (lstCakes.SelectedIndex == 3)
{
cakeCost = 30;
}
break;
}
Any suggestion are appreciated.
Assuming that this is a desktop application, you will probably want to put your prices in a config file so that they can be changed later. You add an <appSettings> block to your App.config file with an entry for each cake and then use the ConfigurationManager.AppSettings[] command to retrieve them.
So if this is a Windows Forms app, then on the form load you can go into your app settings, retrieve the details for all the cakes that you want and then populate your list box with entries for each one (see http://msdn.microsoft.com/en-us/library/z38x31c0.aspx). This way you can dynamically create the text for each entry. If you want each line to contain the price you are going to have to hardcode it into the line's text. (I think that is what you are asking...)
One final note. You shouldn't use + to concatenate strings. Strings in C# are immutable -- that means that the string itself cannot be modified (the reason why is a whole other topic that I can explain if you wish). In order to concatenate two strings with "+", C# needs to create a third string and fill it with the contents of the first two, and this drains performance. To concatenate strings more efficiently, use either a StringBuilder object and the Append() method, or use String.Format() which works the same way.
Immutable strings:
Strings at their core are arrays of characters. Just as you cannot resize an array, you cannot resize a string. This is because arrays are stored on the stack... the stack is a piece of memory which is filled with instructions to run your program that are all "stacked" on top of each other. Stack memory is pre-allocated and for all intents and purposes you cannot dynamically change the memory footprint of objects on the stack. You can have an array of 10 ints containing 5 ints and 5 empty spaces, but you cannot take an int[5] and change it to an int[10]. If you want to add 5 more ints to an int[5] you need to instantiate a new int[10] and fill it up. The same thing goes for a string.
The solution to the array resizing problem is dealt with using Lists and their derivatives. They function using heap memory. This is similar to how a StringBuilder object functions. If you want to know more about stack and heap memory and how it affects how your program runs, this might help you understand a bit better http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx. It is really important to know, because it can explain a lot of mysteries that will stump beginner programmers. Good for you for asking.
The cake prices could be maintained on a Enum
enum CakePrices{
ChocCake = 20,
VanillaCake = 50
}
Calculate the Cost:
int TotalCost;
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
//The name of the List Items should match the names on the enum,for this to work
TotalCost += (int)Enum.Parse(typeof(CakePrices),
lstCakes.SelectedItems[index].ToString() ,
false)
}
Console.WriteLine("You have ordered:" + strCakes + '\n' + "Total Cost: " + TotalCost);

Print index from array

I am working on a text-based game, and I want to print the results in the end.
However, at the moment it only prints the latest input data and not the 5 loops in the array.
This is my array
int[] turnarr = new int[5];
turnarr[x] = turn;
for (int i = 0; i < turnarr.Length; i++)
Console.WriteLine(turnarr[i] + "\t" );
It's hard to be certain, as I only see part of the code, but I suspect that you are recreating the turnarr array in each turn, which would make every entry except the last one zero.
If the value of x never changes then you're only writing to a single item in the array, and thus overwriting it every time with the latest value of turn.
If turn is your last turn value, and x is 4, you will see four zeroes on their own lines and then the value of turn because you are only assigning to the xth index of turnarr
I took a look at your pastebin and tracked the issue down I believe:
The following line:
Console.WriteLine(turnarr[i] + "\t" + windarr[i] + " ms \t" + apmeterarr[x] + "m\t\t" + lenghtarr[x] + " meter\t\t");
you are using i for 2 spots, and x for the other 2 for your index variable...
Change
apmeterarr[x] and
lenghtarr[x]
To
apmeterarr[i] and
lenghtarr[i]

Categories

Resources