Codiqo

Learn C# · lesson 7 of 61 · about 7 minutes

String Methods

Tidy the Slime's move with Trim, ToUpper and Substring, and find out why a string never changes by itself.

What you'll learn

  • Change case and trim spaces
  • Slice with Substring and search with IndexOf
  • Store the string a method returns

The string toolkit

A string comes with methods: actions you call with a dot and brackets.

  • move.Trim() removes spaces at both ends
  • move.ToUpper() and move.ToLower() change the case
  • move.Substring(0, 6) takes 6 characters, starting at position 0
  • move.Substring(7) takes everything from position 7 on
  • move.IndexOf("attack") finds where something starts, or gives -1
  • move.Replace("bounce", "splash") swaps text
  • move.Contains("bounce") is True or False

In C#, the second number in Substring is how many characters, not where to stop.

Using the toolkit

string move = "  bounce attack  ";
move = move.Trim();
Console.WriteLine(move.ToUpper());
Console.WriteLine(move.Substring(0, 6));
Console.WriteLine(move.IndexOf("attack"));
Console.WriteLine(move.Replace("bounce", "splash"));
Console.WriteLine(move.Contains("bounce"));

Output

BOUNCE ATTACK
bounce
7
splash attack
True

Strings never change

move.ToUpper() doesn't change move: it makes a new string in capitals and hands it back. If you don't store what comes back, it's lost. That's why the example says move = move.Trim();.

Store the result

string name = "slime";
name.ToUpper();
Console.WriteLine(name);
name = name.ToUpper();
Console.WriteLine(name);

Output

slime
SLIME

Tip

Methods can be chained: move.Trim().ToUpper() trims first, then makes capitals.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.