Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes. In C#, strings are incredibly powerful and come with many built-in methods to manipulate them.
To find out how many characters are inside a string, you can use the Length property.
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Console.WriteLine("The length of the txt string is: " + txt.Length); // Outputs 26
You can easily convert any string to all uppercase or all lowercase letters using the ToUpper() and ToLower() methods.
string txt = "Hello World"; Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD" Console.WriteLine(txt.ToLower()); // Outputs "hello world"
Combining two or more strings is a very common task. There are two popular ways to do this in modern C#:
You can use the + operator to join strings together.
string firstName = "John "; string lastName = "Doe"; string name = firstName + lastName; Console.WriteLine(name);
String interpolation substitutes values of variables directly into placeholders in a string. To use it, place a dollar sign ($) right before the starting quote, and wrap variables in curly braces {}. This is often much easier to read!
using System;class Program { static void Main() { string firstName = "John"; string lastName = "Doe"; // Using string interpolation string name = $"My full name is: {firstName} {lastName}"; Console.WriteLine(name); } }
Which character is used to denote an interpolated string in C#?