Skip to content

Working with Strings

The Course
•
25 min study

Real text is messy: extra spaces, inconsistent capitals, blank entries. A string comes with methods for cleaning it up. Length is a property, a value that belongs to the string, so it has no parentheses. Methods such as Trim() do have parentheses.

Strings never change

Every string method gives you a new string. The original stays the same. This is called being immutable. Calling Trim() and ignoring the result does nothing useful, and it's one of the most common beginner mistakes in C#.

Which line actually changes title? C#
string title = "  Read chapter  ";

title.Trim();
Console.WriteLine(title.Length);

title = title.Trim();
Console.WriteLine(title.Length);

Console.WriteLine(title.ToUpper());
Console.WriteLine(title);
Check your prediction
Text
16
12
READ CHAPTER
Read chapter

Only the assignment title = title.Trim(); changed which text title refers to. ToUpper() returned a new string, which was printed and then discarded.

Searching and slicing

The characters in a string are numbered from 0, so the first one is at index 0 and the last is at Length - 1. A single character is a char, written in single quotes. Substring(start, length) copies part of a string; IndexOf finds where something is, or gives -1 if it isn't there.

Positions in a string C#
string file = "notes.txt";

Console.WriteLine(file[0]);
Console.WriteLine(file[file.Length - 1]);
Console.WriteLine(file.IndexOf('.'));
Console.WriteLine(file.Substring(0, 5));
Console.WriteLine(file.Contains("note"));
Console.WriteLine(file.EndsWith(".txt"));
Console.WriteLine(file.IndexOf('z'));
Check your prediction
Text
n
t
5
notes
True
True
-1

Reading past the end is a mistake that the compiler can't catch, because it depends on the values at run time. file[9] throws an exception, which you'll learn about on Day 6. Try it and read the message.

Comparing and testing text

== compares strings by their contents, and it's case sensitive. To ignore case, pass an option to Equals. To test for missing text, string.IsNullOrWhiteSpace is the standard tool, as it treats an empty string and a string of spaces alike.

Equal or not? C#
string topic = "Loops";

Console.WriteLine(topic == "Loops");
Console.WriteLine(topic == "loops");
Console.WriteLine(topic.Equals("loops", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.IsNullOrWhiteSpace(""));
Console.WriteLine(string.IsNullOrWhiteSpace("   "));
Console.WriteLine(string.IsNullOrWhiteSpace(" x "));
Check your prediction
Text
True
False
True
True
True
False

Splitting and joining

Split breaks a string into an array of pieces at a separator. An array is a fixed-size row of values; string[] means an array of strings. You'll work with collections properly in the next lesson. string.Join goes the other way, gluing pieces back together.

Take text apart and put it back C#
string line = "Loops,Lists,Records";
string[] topics = line.Split(',');

Console.WriteLine(topics.Length);
Console.WriteLine(topics[1]);
Console.WriteLine(string.Join(" > ", topics));
Check your prediction
Text
3
Lists
Loops > Lists > Records

Your turn

Exercise

Clean a task title

Write CleanTitle(string text). It removes surrounding spaces. If nothing is left, it returns Untitled. If more than 10 characters remain, it keeps the first 10 and adds .... Otherwise it returns the trimmed text. Print the result for " Read ", " " and "Practice for an hour".

Your workspace C#
string text = "  Read  ";
Console.WriteLine(text);
Hint 1: the idea

Trim first and keep the result in a variable, because every later decision depends on the trimmed version.

Hint 2: a first step

Start with a method that does nothing except trim and return, and make the first call print Read.

Show one solution
C#
Console.WriteLine(CleanTitle("  Read  "));
Console.WriteLine(CleanTitle("   "));
Console.WriteLine(CleanTitle("Practice for an hour"));

static string CleanTitle(string text)
{
    string trimmed = text.Trim();
    if (trimmed.Length == 0)
    {
        return "Untitled";
    }
    if (trimmed.Length > 10)
    {
        return trimmed.Substring(0, 10) + "...";
    }
    return trimmed;
}
Text
Read
Untitled
Practice f...

Trimming first means the other two rules see the real title: " " becomes empty and gets Untitled, and spaces around a long title don't count towards its length. The length check uses > 10, so a title of exactly 10 characters is kept whole.

Test a title of exactly 10 characters and one of exactly 11. Which of them gets ...? Change > to >= and see which of those two tests shows the difference.

Was this article helpful?

Your response is saved on this device.