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#.
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
16
12
READ CHAPTER
Read chapterOnly 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.
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
n
t
5
notes
True
True
-1Reading 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.
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
True
False
True
True
True
FalseSplitting 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.
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
3
Lists
Loops > Lists > RecordsYour turn
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".
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
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;
}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.
Completion is saved in this browser only. It does not measure mastery.