Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Hello! First of all I would like to thank every single one of you who has helped me so far learning and understanding all the questions I've been asking.


Now.. I have this software that I am working on (its working) and its really simple, well I understand 85% of it the rest I got help with but he didnt explain it very well..


What I need help with is simplify some code (Dummy it down) and explain what it means. Everything with the comment //This I dont really understand, so if possible, could someone comment it out to explain why its there and what it exactly does.

Thank you so much! :D




C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Arrays
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int[] numbers = new int[5];
        List<int> numbersList = new List<int>();
        string text = System.IO.File.ReadAllText(@"C:\Users\Developer\Documents\Visual Studio 2015\Projects\Arrays\hash.txt");
        string[] displayStringArrays = null; //This

        private void Form1_Load(object sender, EventArgs e)
        {
            //numbers[0] = 12;
            //numbers[1] = 10;
            //numbers[2] = 25;
            //numbers[3] = 10;
            //numbers[4] = 15;
            //numbersList.Add(23);
            //numbersList.Add(32);
            //numbersList.Add(35);
        }
        //Array Print
        private void button1_Click(object sender, EventArgs e)
        {
            displayArrays.Text = listText.Text;
        }
        //List Print
        private void button2_Click(object sender, EventArgs e)
        {
            displayStringArrays = text.Split('\n').ToArray(); //This
            foreach (var item in displayStringArrays) //This
            {
                displayArraysString.Text += item;

                if (listText.Text == item.Substring(0, item.Length - 1) || listText.Text == item) //This
                {
                    MessageBox.Show("Found a match!");
                    return;
                }
                else
                {
                    //Something.
                }
            }

        }

        private void displayArraysString_TextChanged(object sender, EventArgs e)
        {

        }
    }
}


What I have tried:

I've tried googleing but no "simple" answers were found
Posted
Updated 10-May-16 4:39am

C#
string[] displayStringArrays = null;

Is declaring a array of strings called displayStringArrays and initialising the value of the array to null - i.e. it has been declared but has no value (yet). The = null is not really necessary.
C#
displayStringArrays = text.Split('\n').ToArray(); 

This line is taking the contents of the variable text and splitting it into separate strings wherever it finds a carriage return/line feed ('\n'). It places each of the strings into the array that was declared earlier.
C#
foreach (var item in displayStringArrays)
Is saying - execute the following block of statements (between the matching braces { and }) once for each one of the strings in the array. It's similar to using
C#
for (int i =0; i < displayStrings.Length; i++)

C#
if (listText.Text == item.Substring(0, item.Length - 1) || listText.Text == item)
This is comparing the Text property of a control called listTextto the string that is currently the subject of the foreach loop - it will be checked against all of the strings in the array one by one. The comparison is checking to see if the string in the array exactly matches the text in the control OR (||) if the text in the control starts with the same text as the string (Substring)
 
Share this answer
 
v2
Comments
BladeLogan 10-May-16 10:25am    
Thank you so much that made things alot more clear! You said that " string[] displayStringArrays = null; " isnt necessary, could I remove the whole line?
CHill60 10-May-16 10:28am    
No - you can't remove it as you are using the variable across several methods and it has to be declared before it can be used. If you just declare it within each method, you will actually get a different variable - check out Variable and Method Scope in Microsoft .NET[^].

Just remove the =null bit ... i.e. string[] displayStringArrays;
Sergey Alexandrovich Kryukov 10-May-16 10:53am    
How do you know it's '\n'? This part is potentially incorrect.
—SA
CHill60 10-May-16 10:58am    
Well the line of code the OP was questioning was the overload of Split that takes a single parameter - a char array. In this instance an array with a single entry '\n'. Or am I missing something?
Sergey Alexandrovich Kryukov 10-May-16 11:11am    
I see absolutely no evidence that this is not '\n', '\r' or a combination of anything. It depends on the origin of data, such as platform, so cross-platform System.Environment.NewLine can be used. But it only works if the file is created on the same platform, which is likely, in this case.
—SA
Have a read of these

Arrays Tutorial (C#)[^]
String.Split Method (System)[^]
String.Substring Method (Int32, Int32) (System)[^]

C#
string[] displayStringArrays = null;


This means that displayStringArrays is an array of strings, however it is simply being defined at this point, it doesn't actually contain an array of strings just yet. The other thing of note is that at this point we don't know the size of the array either, we just know that this variable can now contain an array of strings in the future.

C#
displayStringArrays = text.Split('\n').ToArray(); //This


First off the code above doesn't need the ToArray

C#
displayStringArrays = text.Split('\n'); //This


Split converts a single string into an array of strings using the character you supply as the separator. So if text was "abcabcabcdef" then Split('c') on that text would result in an array like this

C#
displayStringArrays[0] = "ab";
displayStringArrays[1] = "ab";
displayStringArrays[2] = "ab";
displayStringArrays[3] = "def";


So when you Split('\n'), \n is the code for new line, you are taking a chunk of text that has multiple lines and creating an array where each element in that array is a line. So if the text was;

how now
brown cow


you'd have an array like

C#
displayStringArrays[0] = "how now";
displayStringArrays[1] = "brown cow";


C#
foreach (var item in displayStringArrays)


That line will cause the code in the { } block to loop once for each item in your array, so the first iteration "item" will be displayStringArrays[0], the second iteration will be displayStringArrays[1] and so on.

Basically what the code is doing is splitting the text in the file into an array of lines, and processing each line at a time with that line being in "item".

C#
if (listText.Text == item.Substring(0, item.Length - 1) || listText.Text == item)


That's not good code. The "||" means "or", so if the statement to the left or it or the statement to the right is true the "if" evaluates as true. The statement to the right (listText.Text == item) is straightforward, it means if the text in that textbox is the same as "item".

The code to the left is comparing the text box with the substring of "0, length-1" of "item". That means starting at character 0 (the first) and going to the length of item minus 1, ie the second but last character. So if "item" is "Hello" then that substring is

"Hell"

The length of Hello is 5, so starting at the first character and taking the 4 characters you get "Hell"

So it item is "Hello" and listText.Text is "Hell" + <any character> then that will resolve to true. So if listText is any of these;

Hella
Hellb
Hellc
Helld
Helle

then

C#
listText.Text == item.Substring(0, item.Length - 1)


will resolve to true. I assume that logic was done for a reason and I am going to further assume it is to capture either a trailing space, so a trailing carriage return. As we can't see your data we don't know, but that is my guess. If that Is right then there are better ways of handling that, eg changing the Split to this

C#
displayStringArrays = text.Split(new char[]{'\r','\n'}, StringSplitOptions.RemoveEmptyEntries);


If the code is there to ignore trailing spaces then you can use Trim()

C#
if (listText.Text.Trim() == item.Trim())


As it is the code has introduced a bug that is going to give unintended results. Eg the line might be

"Mend"

and your compare text might be "Men" and that is going to register a match when it isn't.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900