Back to Top

Working with Characters and Strings


I've got a confession to make: characters are considered variables in C#, being very similar to integers. I chose to discuss them in this tutorial, though, because a string is made from one or more chars.


Create a new Windows Forms project, and then add a button and a label to it. Set the button text to "Chars and Strings" and the label "(Name)" to "Result". Then, delete the default "Text" label property; we don't want our label to display anything for now. Finally, resize the form until it looks similar with the one below.


resized formDouble click the button, and then type in the two lines of code highlighted in the image below.


characterBuild and run the application, and then click its button; the program will display the "a" character.


Fortunately, it is easy to define strings in C#. A string is nothing more than a collection of characters, which are stored in adjacent memory cells.


Here's how you can define a string:


string myName = "Depak Holst"; // use your name here


And here's how our button code looks now.


string exampleSince our label has a Text property which works with strings, we can set Result.Text to the string which contains the name. Run the program, click the button, and the program will display your name on the screen.


One more thing: you can see that we have used a double slash, followed by "use your name here". Anytime the compiler sees the "//" sequence, it will ignore the text that follows it. This allows us to use comments, the way I did it, thus making our code more readable, adding explanations for other programmers that may use some of our code, etc.


C# allows us to play with strings using various methods. Here are a few examples and the results of their execution.


        private void button1_Click(object sender, EventArgs e)

        {

            string myName = "John ";

            string mySurname = "Doe";

            Result.Text = myName + " " + mySurname; // add a space to separate the name and surname

        }


name surname        private void button1_Click(object sender, EventArgs e)

        {

            string myName = "John Doe";

            Result.Text = "My name contains " + myName.Length + " characters"; // counts the number of characters in a string          

        }


count characters

        private void button1_Click(object sender, EventArgs e)

        {

            string myName = "John Doe";

            Result.Text = myName.ToUpper() + "     " + myName.ToLower(); // convert the string to upper case and lower case

        }


upper lowerThese are just a few examples, but I hope that they have proved the tremendous power behind the C# strings. I'll see you in the following tutorial, when we will learn how to change the UI elements' properties through code.