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 endsmove.ToUpper()andmove.ToLower()change the casemove.Substring(0, 6)takes 6 characters, starting at position 0move.Substring(7)takes everything from position 7 onmove.IndexOf("attack")finds where something starts, or gives -1move.Replace("bounce", "splash")swaps textmove.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
TrueStrings 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
SLIMETip
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.