Get up to 80 % extra points for free! More info:

Lesson 10 - Strings in C# .NET - Split and Join

In the previous exercise, Solved tasks for C# .NET lesson 9, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on split and join in C# .NET instead of a thorough-full lesson? Here it is:

Using String methods (insert/remove/sub­string):

Console.WriteLine("I would banish all of these Internets.".Insert(8, "not "));
Console.WriteLine("I would not banish all of these Internets.".Remove(8, 4));
Console.WriteLine("I would not banish all of these Internets.".Substring(2, 5));
Console.WriteLine("alpha".CompareTo("bravo"));

Using the Split() and Join() methods:

string text = "I like C# .NET";
string[] words = text.Split(' '); // split the text by spaces
Console.WriteLine(words[2]); // print the third word
words[1] = "love"; // change the second word
text = string.Join(" ", words); // join it back to the text
Console.WriteLine(text);

Would you like to learn more? A complete lesson on this topic follows.

In the previous tutorial, Solved tasks for C# .NET lesson 9, we made clear that C# .NET strings are essentially arrays of characters. In today's lesson, we're going to explain other string methods that I have intentionally kept from you because we didn't know that strings are similar to arrays :)

We can call many methods which we know from arrays in a similar fashion. For example: First(), Last(), IndexOf() and others.

When you create an arbitrary variable and write a dot after it, Visual Studio will show us all of the available methods, properties, and variables, that we can call on that variable (we'll go deeper into this in the OOP course). This tool is called IntelliSense and it'll make our work easier and complete a code for us. Let's try it out:

String methods in Visual Studio - C# .NET Basic Constructs

The same suggestion can also be accessed by pressing Ctrl + Spacebar when the text cursor is on the dot. Of course, this applies to all variables and classes (we'll use it further along the way, as well). The methods are ordered alphabetically and we can list them using the arrow keys. VS shows us the description of the methods, what they do, and what parameters do they need.

Let's talk about the following methods and demonstrate them on simple examples:

Additional string methods

Insert()

Inserts a substring into a string at a specified position. The parameters are the position in the string and the substring.

Console.WriteLine("I would banish all of these Internets.".Insert(8, "not "));

The output:

Console application
I would not banish all of these Internets.

Remove()

Removes characters from the given position to the end of the string. The parameter is the numerical position. We can also enter a second parameter which specifies the number of characters we want to be removed.

Console.WriteLine("I would not banish all of these Internets.".Remove(8, 4));

The output:

Console application
I would banish all of these Internets.

Substring()

Returns a substring from the given position to the end of the string. We can enter the second parameter which specifies the length of the substring.

Console.WriteLine("I would not banish all of these Internets.".Substring(2, 5));

The output:

Console application
would

CompareTo()

It allows us to compare two strings alphabetically. Returns -1 if the first string is before the string in the parameter, 0 if they are equal and 1 if the string is after one in the parameter:

Console.WriteLine("alpha".CompareTo("bravo"));

The output:

Console application
-1

Now let's look at two more, very useful, string methods.

Split() and Join()

From the previous tutorial, we know that parsing strings character by character can be rather complicated. Even though we made a fairly simple example. Of course, we'll encounter strings all the time, both in user inputs, e.g. from the console or from input fields in windows form applications, and in TXT and XML files. Very often, we're given one long string, a line in a file or in the console, in which there are multiple values separated by separators, e.g. commas. In this case, we're talking about the CSV format (Comma-Separated Values). To be sure that we all know what we're talking about, let's look at some sample strings:

Jessie,Brown,Wall Street 10,New York,130 00
.. ... .-.. .- -. -.. ... --- ..-. -
(1,2,3;4,5,6;7,8,9)
  • The first string clearly represents a user. We could, for example, store users into a CSV file (one per line).
  • The second string is Morse code characters and uses the space character as the separator.
  • The third string is a matrix of 3 columns and 3 rows. The column separator is a comma, whereas the row separator is a semicolon.

We can call the Split() method on a string, which takes a separator, char, or even an array of separators as a parameter. It'll then split the original string using separators into an array of substrings and return it. This will greatly simplify value extraction from strings for our current intents and purposes.

The Join() method is called directly on the string data type and vice versa allows us to join an array of substrings into a single string using a specified separator. The parameters are a separator and an array. The output of the method is the resulting string.

Right then, let's see what we've got up until now. We still don't know how to declare objects, users, or even work with multidimensional arrays, i.e. matrices. Nevertheless, we want to make something cool, so we'll settle with making a Morse code message decoder.

Morse code decoder

We'll start out by preparing the program structure, as always. We need two strings for the messages, one for a message in Morse code, the other one will be empty for now and we'll store the results of our efforts there. Next, we need letter definitions (as we had with vowels). Of course, we'll also need the Morse code versions of the letter definitions. We can store letters as a single string since they only consist of one character. The Morse code letters consist of multiple characters, therefore we have to specify them using an array.

The structure of our program should now look something like this:

// the string which we want to decode
string s = ".. -.-. - ... --- -.-. .. .- .-..";
Console.WriteLine("The original message: {0}", s);
// the string with a decoded message
string message = "";

// array definitions
string alphabetChars = "abcdefghijklmnopqrstuvwxyz";
string[] morseChars = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."};

We could also add other Morse characters such as numbers and punctuation marks, but we won't worry about them for now. We'll split the string s with the Split() method into an array of substrings containing the Morse characters. We'll split it by the space character. Then we'll iterate over the array using a foreach loop:

// splitting the string into Morse characters
string[] characters = s.Split(' ');

// iterating over Morse characters
foreach (string morseChar in characters)
{

}

Ideally, we should somehow deal with cases when the user enters e.g. multiple spaces between characters (users often do things of the sort). In this case, Split() creates one more empty substring in the array. We should then detect it in the loop and ignore it, but we won't deal with that in this lesson.

In the loop, we'll attempt to find the current Morse character in the morseChars array. We'll be interested in its index because when we look at that same index in the alphabetChars array, there will be the corresponding letter. This is mainly because both the array and the string contain the same characters which are ordered alphabetically. Let's place the following code into the loop's body:

char alphabetChar = '?';
int index = Array.IndexOf(morseChars, morseChar);
if (index >= 0) // character was found
    alphabetChar = alphabetChars[index];
message += alphabetChar;

First, the alphabetical character is set to '?' since it may very well be that we don't have it defined in our array. Then we try to determine its index. If it succeeds, we assign the character from alphabetic characters at its index to alphabetChar. Finally, we add the character to the message. The += operator works the same as message = message + alphabetChar.

Now, we'll print the message and add ReadKey():

Console.WriteLine("The decoded message: {0}", message);
Console.ReadKey();

The output:

Console application
The original message: .. -.-. - ... --- -.-. .. .- .-..
The decoded message: ictsocial

Done! If you want to train some more, you can create a program which would encode a string to the Morse code. The code would be very similar. We'll use the Split() and Join() methods several more times throughout our courses.

Special characters and escaping

Strings can contain special characters which are prefixed with backslash '\'. Mainly, the \n character, which causes a line break anywhere in the text, and \t, which is the tab character.

Let's test them out:

Console.WriteLine("First line\nSecond line");
Console.ReadKey();

The \ character indicates a special character sequence in a string and can be used also e.g. to write Unicode characters as \uxxxx where xxxx is the character code.

The problem might be when we want to write \ itself, in this case we've to escape it by writing one more \:

Console.WriteLine("This is a backslash: \\");

We can escape a quotation mark in the same way, so C# wouldn't misinterpret it as the end of the string:

Console.WriteLine("This is a quotation mark: \"");

It could get troublesome when we want to write a longer path to some file and there are lots of backslashes in it. Microsoft was aware of this issue and introduced the @ modifier that enables C# to automatically escape a whole string declared in the code:

Console.WriteLine(@"C:\Users\David\Dropbox\ictsocial");

Inputs from the console and input fields in Windows form applications are, of course, escaped automatically, so the user wouldn't be able to enter \n, \t, etc.. Programmers are allowed to write these characters in the code, so we have to keep escaping in mind.

Today we basically finished the on-line course on the C# .NET language basic structures. In the next lesson, Solved tasks for C# .NET lesson 10, we'll look at a bonus episode about multidimensional arrays and we'll briefly talk about the Math class and advanced console control. Nothing will surprise you from the basic language constructs anymore :) In fact, you could potentially start working with objects now, but I would suggest for you to read the next few lesson. You all still have a long way to go, but your future looks bright!

In the following exercise, Solved tasks for C# .NET lesson 10, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 25x (35.32 kB)
Application includes source codes in language C#

 

Previous article
Solved tasks for C# .NET lesson 9
All articles in this section
C# .NET Basic Constructs
Skip article
(not recommended)
Solved tasks for C# .NET lesson 10
Article has been written for you by David Capka Hartinger
Avatar
User rating:
7 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities