Lesson 16 +10 XP

C# Strings

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

Declaring a string

Code

csharp
string greeting = "Hello";

### Console.WriteLine(greeting);

String length

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

Code

csharp
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

### Console.WriteLine(txt.Length);   // 26

Uppercase and lowercase

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

Code

csharp
string txt = "Hello World";

### Console.WriteLine(txt.ToUpper());   // HELLO WORLD

### Console.WriteLine(txt.ToLower());   // hello world

Concatenation

The + operator joins strings:

Code

csharp
string firstName = "John";
string lastName = "Doe";
string name = firstName + " " + lastName;

### Console.WriteLine(name);   // John Doe

String interpolation

Use

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

Code

csharp
string firstName = "John";
string lastName = "Doe";
string name = $"{firstName} {lastName}";

### Console.WriteLine(name);   // John Doe

Access characters

Index positions start at 0:

Code

csharp
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

` | new line |

Code

csharp
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
    amp;quot;{var}"
    is cleaner.
  • Indexes start at 0; use \\ to escape special characters.