how to put string into an array C# - c#

i need to put the contents of an text box that is a string into an array.
i have seen lots of people asking how to put each letter as an index in the array but i want the whole string in one index.
for context
i am making an application for a hotel booking for an assignment, it takes a name, room number and length of stay. it also stores room size with radio buttons. then there is another button and a textbox that when you type a room size (Single, double or triple) it will display how many people have book that room type and the name on the booking.
any help would be greatly appreciated. here is what i have done and i picture of what the application is meant to look like.
namespace Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// MessageBox.Show("Initalize");
}
string[] CusName = new string[150];
int[] RNumber = new int[150];
int[] nights = new int[150];
string[] RSize = new string[150];
string name;
bool blnnumcheck;
bool blnNightsCheck;
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Load");
}
private void TxtName_TextChanged(object sender, EventArgs e)
{
name = TxtName.Text;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
string size;
int Roomnum, night;
blnNightsCheck = int.TryParse(txtLengthofStay.Text, out night);
if (!System.Text.RegularExpressions.Regex.IsMatch(TxtName.Text, "([a-zA-Z])"))
{
MessageBox.Show("Invalid Name Please try again");
}
blnnumcheck = int.TryParse(txtRoomNumber.Text, out Roomnum);
if (!blnnumcheck )
{
MessageBox.Show("Invalid Room Number Please try again" );
}
if (Roomnum >= 150)
{
MessageBox.Show("Invalid Room Number Please try again");
}
}
}
}
this what the completed one is supposed to look like

try this:
List<string> myArray = new List<string>();
myArray.Add(myTextBox.Text);

string data = "Hello, Good Morning";
string[] stringArray = new string[]{ data };
Console.WriteLine(stringArray[0]);

If you know how to create arrays, continue reading, if you don't, jump to the content below the horizontal line.
You create an int array using int[], right? So if you want to create a string array, use string[]!
Here is more code:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
That is simple enough, right? You can do all the things you can do with an int array to a string array.
If you don't know how to create an array, start to read here
You declare an array like this:
type[] array_name = new type[length];
And you can put stuff in the array like this:
array_name[index] = some_stuff;
Thus, you can create an array of strings like this:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
Just remember, whatever type you want an array to be, write whatever type followed by [] and give it a name!
You can loop through a 2D array like this:
for (int i = 0 ; i < maxX ; i++) { // maxX is the maximum index of the array in the first dimension
for (int j = 0 ; j < maxY ; j++) {
//you can access the array here with array[i][j]
}
}

Related

Can't print index and sum of an array

I have homework. I have to make a program which can input the length of an array with the value in it. After I click the "process" button, the program will make an output of index and value with the result sum and average from the array.
I'm stuck and couldn't print the index and the value to the multiple textbox below process button.
I'm expecting the output will look like this:
Here's the code which I'd been successful write so far:
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i];
}
boxSum.Text = Convert.ToString(sum);
}
}
}
Please, help me.
Here is the code for you (boxAvg is for average)
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i-1];
}
//Refer your list box here to add newly added values to the list
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum / count); //calculate the average
}
}
}
Given that the array already has data :
private void Display()
{
var columnHeader1 = "Index Value\n";
multilineTextBox1.Text =
columnHeader1 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5}"));
boxSum.Text = vArray.Sum();
boxAvg.Text = vArray.Average();
var columnHeader2 = "Index Value Histogram\n";
multilineTextBox2.Text =
columnHeader2 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5} {new String('*', x)}"));
}
String.Join(separator, string[]), To join each row with a Carriage return/Line feed.
.Select((x,i)=> (...), To get each elment of the array an its index.
$"", For the easy string interpolation
{i+1,5}, To display the index i padded on 5 char.
new String('*', x)}, To create a string of N time the same char.
Console demo

select randomly from string array without repetitions

Good day I have some problem regarding selecting a random string from my string array I am currently developing a guessing word game.
this is my string array:
string[] movie = {"deadpool", "batmanvssuperman", "findingdory", "titanic", "suicidesquad", "lordoftherings", "harrypotter", "jurassicpark", "hungergames", "despicableme" };
while this is the process in selecting a random string to my array, what should i do next, because I want to select the string not repeated.
e.g
when the program starts it will select a string then when i select random string again i want to not select the previous word that i've already selected previously.
string word = movie[r.Next(0, movie.Length)].ToUpper();
Thank you for response! Have a nice day.
Well, simply convert your array to list and shuffle it in random order :
var rand = new Random();
string[] movies = { "deadpool", "batmanvssuperman", "findingdory", "titanic", "suicidesquad", "lordoftherings", "harrypotter", "jurassicpark", "hungergames", "despicableme" };
List<string> randomMovies = movies.ToList();
for (int i = 0; i < movies.Length / 2; i++)
{
var randNum = rand.Next(i, randomMovies.Count);
var temp = randomMovies[randNum];
randomMovies[randNum] = randomMovies[i];
randomMovies[i] = temp;
}
Then you can just take random elements by :
var randomMovie = randomMovies.First();
randomMovies.Remove(randomMovie); // either remove it or use loop to iterate through the list
I sort of like to use Queue collection here :
var moviesQueue = new Queue<string>(randomMovies);
while (moviewQueue.Count > 0)
{
Console.WriteLine(moviewQueue.Dequeue());
}
P.S.
As suggested you don't really need to delete elements from randomMovie, you can save last used index in some field and use it later;
var lastIndex = 0;
var randomMovie = randomMovies[lastIndex++];
Just loop if it's been selected. This is untested code:
private string _last;
private string GetNonRepeatedMovie()
{
string selected = "";
do
{
selected = movie[r.Next(0, movie.Length)].ToUpper();
}
while (selected == this._last);
this._last = selected;
return selected;
}
This should work to select the initial string as well when the application starts.
If you need to keep a memory, convert your list to be a class that contains the name and a field of whether it has been chosen or not.
If you go through all of them, turn this semiphor off and begin again.
class GuessingName
{
public GuessingName(string name){Name = name;}
public string Name;
public bool chosen;
}
class RandomNamePicker{
private List<GuessingName> names;
public RandomNamePicker(){
names = new List<GuessingName>();
names.Add(new GuessingName("movie"));
}
string RandomPicker(){
if(names.All(c=>c.chosen))
names.ForEach(c=>c.chosen=false);
int r1 = r.Next(0, names.Length);
while(names[r1].chosen){
r1= r.Next(0,names.Length);
}
return names[r1].Name;
}
}

Textbox to array declaration in C# windows form

Hi I’m fairly new to c# programming so please bear with me. I’m currently working on a “simple” little program which allows the user to enter 25 values into the same text box and once this has been done I want to be able to display this 25 values in a list box as an array of 5 row by 5 column and I want to find out the largest number in the array.
private void button1_Click(object sender, EventArgs e)
{
int arrayrows = 5;
int arraycolomns = 5;
int[,] arraytimes;
arraytimes = new int[array rows, array columns];
// list_Matrix.Items.Add(tb_First.Text);
for (int i = 0; i != 5; i++)
{
for (int j = 0; j != 5; j++)
{
array times [i,j]= Convert. To Int32(Tb_First.Text);
list_Matrix.Items.Add(array times[i, j].To String());
}
}
}
This is what I've tried for displaying the array in a list box, but it isn't working. This also prevents me from moving to the next section of finding the largest number among them.
You can split your string using .Split(' ') (or any other character or string). This will give you a onedimensional array with 25 elements (if everything was entered). The trick to converting that into a twodimensional array or grid is to use integer division and modulo, the following code would to
String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array
//make an empty grid with the right dimensions first
int[][] grid = new int[5][];
for (int i=0;i<5;i++) {
grid[i] = new int[5];
}
//save our highest value
int maxVal = 0;
//then fill this grid
for (int i=0;i<splitText.Length;i++){
int value = int.Parse(splitText[i]);
//i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid
//i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates'
grid[i%5][i/5] = value;
//check if this value is larger than the one that is currently the largest
if (value > maxVal)
{
maxVal = value;
}
}
This will fill the twodimensional grid array with the split textbox text, and if there are not enough values in the textbox it leaves a 0 in those cells.
At the end you will also have your maximum value.
Try the following (shows by printing the numbers as string). and assuming you enter the numbers in the following way,
'1,2,3,4...'
string[] nums=txtBox.Text.Split(',');
lstBox.Items.Clear();
int colCount=5;
int colIndex=0;
string line="";
foreach(string num in nums)
{
if(colIndex==colCount)
{
lstBox.Items.Add(line);
line="";
colIndex=0;
}
line+= line==""? num : " "+num;
colIndex+=1;
}
if(line!="")
lstBox.Items.Add(line);
Make sure to correct any syntax mistakes, and to change the parameter names to yours.
private void button1_Click(object sender, EventArgs e)
{
int[] ab=new int[10];
string s = textBox1.Text;
int j = 0;
string [] a = (s.Split(' '));
foreach (string word in a)
{
ab[j] = Convert.ToInt32(word);
j++;
}
for (int i = 0; i < 10; i++)
{
label2.Text +=ab[i].ToString()+" ";
}
}

Modify sorting algorithm to work with listboxes?

So I'm trying to figure out to modify this integer sorting algorithm to work with data elements (file names) alphabetically in a listbox but have no idea how?
I understand how the sorting algorithm below works and can implement it using an integer array. However, for listBoxes I can't seem to find any relevant examples on the net.
public partial class MainWindow : Window
{
Random rand = new Random();
int numOfIntegers = 1000;
int[] array;
public MainWindow()
{
InitializeComponent();
array = new int[numOfIntegers];
}
// sort a vector of type int using exchange sort
public void ExchangeSort(int[] array)
{
int pass, i, n = array.Length;
int temp;
// make n-1 passes through the data
for (pass = 0; pass < n - 1; pass++)
{
// locate least of array[pass] ... array[n - 1]
// at array[pass]
for (i = pass + 1; i < n; i++)
{
if (array[i] < array[pass])
{
temp = array[pass];
array[pass] = array[i];
array[i] = temp;
}
}
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ExchangeSort(array);
listBox.Items.Clear();
foreach (int i in array)
{
listBox.Items.Add(i);
}
MessageBox.Show("Done");
}
You could try LINQ:
public void sort(int[] array)
{
array = array.OrderByDescending (a => a).ToArray();
}
If I understand correctly, you're trying to sort strings. To compare strings you could simply use the String.CompareTo() method or if you need more than simple comparison, the StringComparator class should do for most use cases.
If you choose to do it this way, the condition while sorting would be something like this:
if (array[i].CompareTo(array[pass]) < 0)
And the rest of the code would probably stay about the same, except of course changing the int[] to String[].
Now, that being said, I would suggest using a List<String> and just skip doing this work by hand altogether. See List.Sort() for reference.
To be a bit more specific, here's an example based on your code of what I mean.
public partial class MainWindow : Window
{
List<String> items;
public MainWindow()
{
InitializeComponent();
items = new List<String>();
// Fill your list with whatever items you need
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
items.Sort();
listBox.Items.Clear();
foreach (String str in items)
{
listBox.Items.Add(str);
}
MessageBox.Show("Done");
}
}

word search puzzle game

I am trying to create a word search game. the problem is I am unable to insert words into a TableLayoutPanel. When I wrote this, I got a compile error that says "no overload for method 'placewords' takes '5' arguments.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
for (int a = 0; a < tableLayoutPanel1.ColumnCount; a++)
{
for (int b = 0; b < tableLayoutPanel1.RowCount; b++)
{
Label nl = new Label();
int x = r.Next(65, 90);
char c = (char)x;
nl.Text = c.ToString();
tableLayoutPanel1.Controls.Add(nl, a, b);
}
}
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void PlaceWords()
{
string[] words = { "byte", "char" };
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;// continue trying to place the word in // the matrix until it fits
while (placed == false)// generate a new random row and column
{
int nRow = rn.Next(30);// generate a new random x & y direction vector
int nCol = rn.Next(30);// x direction: -1, 0, or 1
int nDirX = 0; // y direction -1, 0, or 1
int nDirY = 0; // (although direction can never be 0, 0, this is null)
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed =PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY);
}
}
}
Your PlaceWords method doesn't accept that many parameters, in fact, it accepts no parameters.
Further more, the way it looks, your PlaceWords is a recursive function that won't exit, leading to a stack overflow.
To fix this, you need to create a second PlaceWords function that accepts all 5 parameters, and does whatever PlaceWords does, and returns a boolean.
It looks like your nested for loops in Form1_Load should be placing random characters into tableLayoutPanel1. You then need to call PlaceWords() which will determine the location and direction to place each word in the words list. Near the end of PlaceWords you are calling PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY) which is supposed to actually put the word into tableLayoutPanel1. This second PlaceWords with 5 parameters should have a different name (I suggest PlaceString); it should not be trying to call the same Placewords method that it is in.
You need to then write the method PlaceString that will look like:
public bool PlaceString(string s, int nRow, int nCol, int nDirX, int nDirY)
{
/* whatever code you need to put the string into tableLayoutPanel1 */
}

Categories

Resources