C# Strings

Strings are used to store text, such as a name, a message, or a whole paragraph. In C# a string is a sequence of characters wrapped in double quotes, and the language gives you many built-in tools to work with them.

Creating a String

You declare a string variable with the string keyword and assign a value inside double quotes. Single quotes are reserved for a single character (the char type), so text always uses double quotes.

A simple string

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

String Length

Every string has a Length property that tells you how many characters it contains, including spaces. Because it is a property, you access it without parentheses.

Counting characters

string name = "C# Programming";
Console.WriteLine("The text has " + name.Length + " characters.");
// The text has 14 characters.

Common String Methods

Strings come with methods that transform or inspect the text. ToUpper() and ToLower() change the case, and Trim() removes extra spaces from the start and end. These methods return a new string and never change the original, because strings in C# are immutable.

Transforming text

string city = "  London  ";

Console.WriteLine(city.ToUpper()); //   LONDON
Console.WriteLine(city.ToLower()); //   london
Console.WriteLine(city.Trim());    // London (spaces removed)

Accessing Characters

You can read a single character from a string by its index using square brackets. Indexes start at 0, so the first character is at position 0, the second at position 1, and so on.

  • The first character of "Hello" is at index 0 (the letter H).
  • The last character of a string is at index Length - 1.
  • Trying to read an index that does not exist throws an IndexOutOfRangeException.

Useful string members

MemberWhat it does
LengthNumber of characters in the string
ToUpper()Returns an uppercase copy
ToLower()Returns a lowercase copy
Trim()Returns a copy with surrounding spaces removed
IndexOf("x")Returns the position of the first match, or -1
Note: Because strings are immutable, methods like ToUpper() do not modify the variable. If you want to keep the change, assign the result back: city = city.Trim();

Exercise: C# Strings

Why are strings in C# considered immutable?