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/substring):
{CSHARP_CONSOLE}
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"));
{/CSHARP_CONSOLE}
Using the Split()
and
Join()
methods:
{CSHARP_CONSOLE}
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);
{/CSHARP_CONSOLE}
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
string
s 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 string
s 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:

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.
{CSHARP_CONSOLE}
Console.WriteLine("I would banish all of these Internets.".Insert(8, "not "));
{/CSHARP_CONSOLE}
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.
{CSHARP_CONSOLE}
Console.WriteLine("I would not banish all of these Internets.".Remove(8, 4));
{/CSHARP_CONSOLE}
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.
{CSHARP_CONSOLE}
Console.WriteLine("I would not banish all of these Internets.".Substring(2, 5));
{/CSHARP_CONSOLE}
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:
{CSHARP_CONSOLE}
Console.WriteLine("alpha".CompareTo("bravo"));
{/CSHARP_CONSOLE}
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()
:
{CSHARP_CONSOLE}
// the string that we want to decode
string s = ".. -.-. - ... --- -.-. .. .- .-..";
Console.WriteLine("The original message: {0}", s);
// the string with the decoded message
string message = "";
// array definitions
string alphabetChars = "abcdefghijklmnopqrstuvwxyz";
string[] morseChars = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."};
// splitting a string into Morse characters
string[] characters = s.Split(' ');
// iteration over Morse characters
foreach (string morseChar in characters)
{
char alphabetChar = '?';
int index = Array.IndexOf(morseChars, morseChar);
if (index >= 0) // character was found
alphabetChar = alphabetChars[index];
message += alphabetChar;
}
Console.WriteLine("The decoded message: {0}", message);
Console.ReadKey();
{/CSHARP_CONSOLE}
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:
{CSHARP_CONSOLE}
Console.WriteLine("First line\nSecond line");
Console.ReadKey();
{/CSHARP_CONSOLE}
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 \
:
{CSHARP_CONSOLE_START}
Console.WriteLine("This is a backslash: \\");
{CSHARP_CONSOLE_END}
We can escape a quotation mark in the same way, so C# wouldn't misinterpret it as the end of the string:
{CSHARP_CONSOLE}
Console.WriteLine("This is a quotation mark: \"");
{/CSHARP_CONSOLE}
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:
{CSHARP_CONSOLE}
Console.WriteLine(@"C:\Users\David\Dropbox\ictsocial");
{/CSHARP_CONSOLE}
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 26x (35.32 kB)
Application includes source codes in language C#