5.0: Strings
STRINGS
In this module we'll study String types in more depth, and study three ways to manipulate strings.
Description
Strings, as briefly mentioned in a previous module, are just a collection of characters that can be stored and used throughout an application in different ways. Almost any text, single character, or number can be a string in C#. Strings are initialized by using double quotes in C#.
File Location
Right click on the solution. Click Add > New Project.
Select Console App (.NET Framework).
Name it
05_strings
.Write your code for this module within the
Program.cs
of that project.
Declaring and Initializing Strings
See if you can remember how to do the following things:
declare a string called myName, but don't give it a value yet.
Declare a string and initialize it by giving it a value.
Answers
string myName;
string wholeName = "Douglas Crockford"
Joining Strings
In this module we'll explore common ways to manipulate strings.
Three Types of string manipulation
There are three common ways of manipulating strings in C#:
Concatentation
Composite Formatting
Interpolation
Concatenation
Let's start with string concatenation. In the Program.cs
file in 05_strings, add the following code:
With concatenation we use the +
operator to combine two strings. Notice the space after are and before the closing ". If there was no space, you would need to add one, like this:
Composite Formatting:
Composite formatting is another common way of manipulating strings. Add the following code to your Program.cs file:
Take a note of a few details here: 1. Composite formatting uses curly braces inside the string and a number inside the curly brace. Notice that the first variable is a 0 value in the curly brace, like an array.
A comma follows the string, then each variable name is added.
String Interpolation:
String interpolation is another common method of manipulating strings. Code and study the following:
Note a few things: 1. String interpolation requires that we use the $
before the string. 2. The dollar sign allows us to pass variables in directly to the curly braces.
Challenge
Practice these 3 ways of joining strings together in your
Program.cs
file.
Last updated