53
loading...
This website collects cookies to deliver better user experience
At the end of this lesson, you should be able to answer the following:
Length
which returns the number of characters in the string. To get the length, attach .Length
to a string value or variable.// Calling Length directly from a string
Console.WriteLine("12345".Length);
// Calling Length from a string variable
var someString = "abcdef";
Console.WriteLine(someString.Length);
string
variables, one to hold a first name and one for a last name.var firstName = "Jane";
var lastName = "Shepard";
+
operator. This is called string concatenation.var firstName = "Jane";
var lastName = "Shepard";
var name = firstName + lastName;
Console.WriteLine(name);
name
contains a new string, the value JaneShepard
.firstName
or before lastName
. We could also just add a space string between the two variables." "
) between the expression firstName + lastName
. Remember to use another +
to add this new string into the mix!var firstName = "Jane";
var lastName = "Shepard";
var name = firstName + " " + lastName;
Console.WriteLine(name);
+
, we could insert our strings into a template string. This is called string interpolation.var firstName = "Jane";
var lastName = "Shepard";
var name = $"{firstName} {lastName}";
Console.WriteLine(name);
name
is different.$
.firstName
and lastName
are inside the string.firstName
and lastName
are wrapped in curly braces {}
.{firstName}
and {lastName}
.name
has a template string assigned to it. $
before the string value. Then we inserted the variables we wanted by wrapping them in curly braces and placing them in their desired positions inside the string. Shepard, Jane
instead, we can change the template string like this:$"{lastName}, {firstName}"
name
with this template string and run the code. The output should be Shepard, Jane
.@
character in front of a string value.var multiLine = @"This string spans
multiple lines
and keeps the spaces too!";
Console.WriteLine(multiLine);
Console.WriteLine()
statement.Question
Why would one use string interpolation over concatenation?
Question
Find the error in this code and fix it. The output should be I came, I saw, I conquered.
var action1 = "I came";
var action2 = "I saw";
var action3 = "I conquered.";
var actions = action1 + ", " + action2 ", " + action3;
Console.WriteLine(actions);
Challenge
Copy the code in the question above and change it to use string interpolation. Replace actions
with a template string. The output should be I came, I saw, I conquered.
Challenge
Make a Fill-In-The-Blanks story!
Come up with a story that has 3 or 4 sentences. Replace a word in each sentence with a variable. Declare those variables with initial values and print out the complete story.
Sample story:
var story = @"Three little _________,
They lost their __________,
And they began to ________.";