Lesson 16 +10 XP

C# Strings

C# Strings

A string is a sequence of characters stored in double quotes.

Declaring a string

string greeting = "Hello";
Console.WriteLine(greeting);

String length

Use .Length to find how many characters a string has:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine(txt.Length);   // 26

Uppercase and lowercase

.ToUpper() and .ToLower() change the case:

string txt = "Hello World";
Console.WriteLine(txt.ToUpper());   // HELLO WORLD
Console.WriteLine(txt.ToLower());   // hello world

Concatenation

The + operator joins strings:

string firstName = "John";
string lastName = "Doe";
string name = firstName + " " + lastName;
Console.WriteLine(name);   // John Doe

String interpolation

Use

quot;..." and place variables inside { }:

string firstName = "John";
string lastName = "Doe";
string name = 
quot;{firstName} {lastName}"; Console.WriteLine(name); // John Doe

Access characters

Index positions start at 0:

string myString = "Hello";
Console.WriteLine(myString[0]);   // H
Console.WriteLine(myString[1]);   // e

Special characters

Use the backslash \ to escape characters inside strings:

EscapeMeaning
\'single quote
\"double quote
\\backslash
\nnew line
\ttab
string txt = "We are the so-called \"Vikings\" from the north.";

TL;DR

  • Strings are text in double quotes.
  • .Length, .ToUpper(), .ToLower() are handy.
  • + concatenates; interpolation with
    quot;{var}"
    is cleaner.
  • Indexes start at 0; use \\ to escape special characters.