Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed C# Basics!
You have completed C# Basics!
Preview
Let's learn how to join strings together using concatenation.
- Our printed question is running up against the space where the user types their answer.
- We need to add a space onto the end of the user
question. - We can do this by taking the
questionstring, and concatenating, or joining, a string consisting of a single space onto the end of it.
// We can concatenate strings.
Console.WriteLine("a" + "b");
Console.WriteLine("some words" + "more words");
// If we want a space between the joined strings, we need
// to add it ourselves.
Console.WriteLine("some words" + " " + "more words");
// We can concatenate strings stored in variables.
string myString = "a string";
Console.WriteLine(myString + " abc");
// Notice that simply concatenating onto a string stored
// in a variable doesn't change the value in the variable.
Console.WriteLine(myString);
// To update the variable, we need to assign the concatenated
// value back to it.
myString += " abc";
Console.WriteLine(myString);
myString += " def";
Console.WriteLine(myString);
- Using string concatenation to fix our
askmethod:
static string Ask(string question)
{
Console.Write(question + " ");
return Console.ReadLine();
}
- Let's print what the user entered so they can confirm it's correct.
static void Main()
{
Console.WriteLine("Welcome to the cat food store!");
string entry = Ask("How many cans are you ordering?");
Console.WriteLine("You entered" + entry + "cans");
}
You entered11cans
- Oops! We need to add spaces surrounding
answer, so fix that:
static void Main()
{
Console.WriteLine("Welcome to the cat food store!");
string entry = Ask("How many cans are you ordering?");
Console.WriteLine("You entered " + entry + " cans");
}
You entered 11 cans
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
To fix this, we need to add a space
on to the end of the user question.
0:00
We can do this by taking the question
string and concatenating or
0:02
joining a string consisting of
a single space on to the end of it.
0:06
To concatenate two strings,
you just type a plus sign between them.
0:16
So this code here we'll join
the strings A and B together and
0:22
this would join the string some words and
more words together.
0:25
Let me save this and run it.
0:28
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up