Lesson 17 +10 XP

More String Methods

More String Methods

Strings have many useful methods. Here are the most common ones.

Contains, StartsWith, EndsWith

Check what's inside a string:

string txt = "The quick brown fox";
Console.WriteLine(txt.Contains("fox"));     // True
Console.WriteLine(txt.StartsWith("The"));   // True
Console.WriteLine(txt.EndsWith("fox"));     // True

IndexOf

Find the position of a character or word:

string txt = "Please locate where 'locate' occurs!";
Console.WriteLine(txt.IndexOf("locate"));   // 7

If not found, IndexOf returns -1.

Substring

Extract part of a string. The second argument is the length:

string txt = "Hello World";
Console.WriteLine(txt.Substring(6, 5));   // "World"

Replace

Swap one piece of text for another:

string txt = "Hello World";
Console.WriteLine(txt.Replace("World", "C#"));   // "Hello C#"

Split

Break a string into parts on a separator:

string data = "apple,banana,cherry";
string[] fruits = data.Split(',');
Console.WriteLine(fruits[1]);   // banana

Trim

Remove leading and trailing whitespace:

string txt = "  hello  ";
Console.WriteLine(txt.Trim());   // "hello"

TL;DR

  • Contains, StartsWith, EndsWith return bools.
  • IndexOf returns a position, -1 if missing.
  • Substring, Replace, Split, Trim transform strings.