Understanding the String Class
A C# string is a read-only sequence of characters; read them by index, write special characters with escape sequences, and understand why strings never change.
Novice · C# · Updated
After this lesson you can
- Read a string's characters by index and find its Length
- Write special characters in a string with escape sequences
- Write a character the keyboard doesn't have, such as é, by its Unicode number with a \u escape
Key takeaways
- A string is characters in order:
team[0]is the firstchar, andLengthsays how many there are, so the last is atLength - 1. - Strings never change. Methods such as
ToUpperreturn a new string, so store it if you want to keep it:name = name.ToUpper();. - Write special characters with escape sequences:
\nfor a new line,\tfor a tab,\"for a double quote,\\for a backslash, and\u00e9for é, by its Unicode number. - An
@in front of a string makes it verbatim, so the backslashes in@"C:\bootcamp\strings"are just backslashes. - The empty string
""has aLengthof 0;string.IsNullOrEmptychecks for it and fornull, which means no string at all.
Text is everywhere in programs: names, addresses, messages, web pages, file contents. In C#, text is a string, and you've used strings since your first program. This chapter looks inside them.
A string is a sequence of characters
A string is an ordered sequence of char values, one per character. Like an array, each character has an index starting at 0, and Length says how many there are:
string team = "Georgia";
Console.WriteLine(team.Length);
Console.WriteLine(team[0]);
Console.WriteLine(team[team.Length - 1]);
7
G
a
team[0] is a char, the single character 'G'. You can loop through a string's characters just as you loop through an array:
string word = "loop";
foreach (char letter in word)
{
Console.Write(letter + "-");
}
Console.WriteLine();
l-o-o-p-
Strings never change
Strings are immutable: once a string exists, its characters can't be changed. You can't assign to team[0]. Every operation that seems to change a string actually makes a new string:
string name = "Vanessa";
string fullName = name + " Jones";
string shouting = name.ToUpper();
Console.WriteLine(name);
Console.WriteLine(fullName);
Console.WriteLine(shouting);
Vanessa
Vanessa Jones
VANESSA
name is still "Vanessa". To keep a changed version, store the new string, even in the same variable: name = name.ToUpper();.
Special characters: escape sequences
Some characters can't be typed straight into a string, such as a double quote (it would end the string) or a new line. You write them as an escape sequence: a backslash followed by a letter or symbol.
| Escape | Means |
|---|---|
\n |
a new line |
\t |
a tab |
\" |
a double quote |
\\ |
a backslash |
Console.WriteLine("Line one\nLine two");
Console.WriteLine("She said \"hello\".");
Console.WriteLine("Name:\tGeorgia");
Console.WriteLine("C:\\bootcamp\\strings");
Line one
Line two
She said "hello".
Name: Georgia
C:\bootcamp\strings
Characters you can't type: Unicode escapes
The stadium's food stand sells a jalapeño dog, and its sign says the coffee comes from Café Luna. On a US keyboard there's no key for ñ or é. You could hunt for the character somewhere and paste it in, but a pasted character is easy to lose when a file is saved with the wrong settings, and it's hard to tell an é from an e at a glance in the code.
Every character has a number. Unicode is the world's list of characters, the letters of every alphabet plus symbols and emoji, and it gives each one its own number. In C#, \u followed by that number, written as four hexadecimal digits, puts the character in a string. Hexadecimal (hex for short) counts in sixteens: after the digits 0 to 9 come the letters a to f, standing for 10 to 15. \u00e9 is read "backslash u, zero zero e nine".
| Escape | Character |
|---|---|
\u00e9 |
é |
\u00f1 |
ñ |
\u00b0 |
° (degrees) |
\u00a9 |
© |
Console.WriteLine("Caf\u00e9 Luna");
Console.WriteLine("Jalape\u00f1o dog");
Console.WriteLine("Kickoff: 72\u00b0F");
Café Luna
Jalapeño dog
Kickoff: 72°F
A \u escape is a single character in the string, like \n, however many letters it takes to write it:
string coffee = "Caf\u00e9";
Console.WriteLine(coffee.Length);
Console.WriteLine(coffee == "Café");
4
True
Every \u needs exactly four hex digits: \u00e9, never \ue9, which doesn't compile. Capital and small hex letters mean the same: \u00E9 is é too. To find a character's number on Windows, open the Character Map app, click the character, and read its number at the bottom of the window (U+00E9, which you write as \u00e9). If your terminal shows a ? instead of the character, the string is still right: that terminal's font can't draw it.
Strings with backslashes: verbatim strings
Windows file paths are full of backslashes. Put @ in front of a string to make it verbatim: backslashes are just backslashes, and nothing is escaped.
string folder = @"C:\bootcamp\strings";
Console.WriteLine(folder);
C:\bootcamp\strings
Empty strings
"" is the empty string: a string with no characters, and a Length of 0. string.IsNullOrEmpty checks for it, and also for null, which means no string at all:
string middleName = "";
Console.WriteLine(middleName.Length);
Console.WriteLine(string.IsNullOrEmpty(middleName));
0
True
Do it: count a letter in a team's name
The stadium's sign maker charges by the letter. Before making a team's banner, they want to know how many of one letter its name needs.
The method gets two values:
team: the team's name, astring("Tennessee").letter: the letter to count, achar('e').
For example, the letter 'e' in "Tennessee":
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| Character | T | e | n | n | e | s | s | e | e |
An 'e'? |
yes | yes | yes | yes |
So CountLetter("Tennessee", 'e') returns 4.
Your job: write the method CountLetter(string team, char letter) so it returns, as an int, how many of the name's characters are that letter.
- Look at every character of
team, from the first to the last. - A capital letter and a small letter are different characters:
'G'is not'g'. SoCountLetter("Georgia", 'g')returns1: the capital G at the start doesn't count. - If the letter isn't in the name, return
0. - If the name is the empty string
"", return0.
Practiced live on the lesson page: write the C# right there and check it.
Do it: put the degree sign on the kickoff banner
Before each game, the stadium's scoreboard shows a banner with the temperature at kickoff, such as Kickoff: 72°F. The scoreboard's program builds that text, and the degree sign isn't on the keyboard.
The method gets one value:
temperature: the temperature at kickoff in degrees Fahrenheit, anint(72).
For example, with 72 the banner is these 13 characters:
| Part | Characters |
|---|---|
| The words | Kickoff: (9, the space included) |
| The temperature | 72 (2) |
| The degree sign | ° (1) |
| The letter F | F (1) |
So KickoffBanner(72) returns "Kickoff: 72°F".
Your job: write the method string KickoffBanner(int temperature) so it returns the banner's text.
- Start with
Kickoff:, a colon and one space after the word. - Then the temperature, then the degree sign, written as its Unicode escape
\u00b0, then a capitalF. - A temperature below zero keeps its minus sign:
KickoffBanner(-5)returns"Kickoff: -5°F".
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
A string is characters in order, numbered from 0, and it never changes in place, and an escape sequence can put any character in it, even one your keyboard doesn't have. Every string method you'll meet next follows from those two facts.