Useful String Methods

Find text with IndexOf, LastIndexOf, Contains, StartsWith and EndsWith, and cut and reshape it with Substring, Split, ToUpper, ToLower, Trim and Replace.

Apprentice · C# · Updated

After this lesson you can

  • Find text in a string with IndexOf, LastIndexOf, Contains, StartsWith and EndsWith
  • Cut and reshape a string with Substring, Split, Trim, Replace, ToUpper and ToLower

Key takeaways

  • IndexOf and LastIndexOf give the index of the first or last match, or -1 if it isn't there; Contains, StartsWith and EndsWith answer true or false.
  • Substring(start, length) takes a length, not an end position; Substring(start) takes everything to the end.
  • Split cuts a string into an array at each separator, and string.Join glues an array's elements back together.
  • Trim, ToUpper, ToLower and Replace each return a new string, so you can chain them, as in typed.Trim().ToUpper().
  • == is exact about case; Equals with StringComparison.OrdinalIgnoreCase ignores it.

The string type comes with dozens of methods. A handful of them do most of the everyday work: finding something in a string, and cutting or reshaping it. Remember that strings never change: each method that "changes" a string returns a new one.

Finding text

IndexOf returns the index of the first place a character or piece of text appears, or -1 if it isn't there. LastIndexOf returns the last.

string phone = "614-555-0182";
string fileName = "season.scores.final.csv";

Console.WriteLine(phone.IndexOf('-'));
Console.WriteLine(phone.LastIndexOf('-'));
Console.WriteLine(fileName.LastIndexOf('.'));
Console.WriteLine(phone.IndexOf('x'));
3
7
19
-1

When you only need a yes or no, these return true or false:

string email = "fan@example.com";

Console.WriteLine(email.Contains('@'));
Console.WriteLine(email.StartsWith("fan"));
Console.WriteLine(email.EndsWith(".org"));
True
True
False

Cutting out part: Substring

Substring(start) returns the text from start to the end. Substring(start, length) returns length characters from start.

The second number is a length, not where to stop. (Other languages, such as Java and JavaScript, use an end position. C# doesn't.)

string fullName = "Glen Williamson";
int space = fullName.IndexOf(' ');

string firstName = fullName.Substring(0, space);
string lastName = fullName.Substring(space + 1);

Console.WriteLine(quot;[{firstName}] [{lastName}]");
[Glen] [Williamson]

IndexOf finds the space at index 4. The first name is the 4 characters from index 0; the last name is everything after the space.

The same idea finds a file's extension, after its last dot:

string fileName = "season.scores.final.csv";
string extension = fileName.Substring(fileName.LastIndexOf('.') + 1);
Console.WriteLine(extension);
csv

Breaking into parts: Split

Split cuts a string wherever a separator appears, and returns the pieces as an array:

string line = "123|Laptop|Electronics|999.99";
string[] parts = line.Split('|');

Console.WriteLine(parts.Length);
foreach (string part in parts)
{
    Console.WriteLine(part);
}
4
123
Laptop
Electronics
999.99

string.Join does the opposite: it glues an array's elements together with a separator between them.

string[] words = { "red", "white", "blue" };
Console.WriteLine(string.Join(", ", words));
red, white, blue

Reshaping: case, spaces and replacing

string typed = "   Ohio State   ";

Console.WriteLine(quot;[{typed.Trim()}]");
Console.WriteLine(quot;[{typed.Trim().ToUpper()}]");
Console.WriteLine(quot;[{typed.Trim().ToLower()}]");
Console.WriteLine("614-555-0182".Replace("-", "."));
[Ohio State]
[OHIO STATE]
[ohio state]
614.555.0182
  • Trim removes spaces (and tabs and new lines) from both ends. TrimStart and TrimEnd do one end only.
  • ToUpper and ToLower change the case of every letter.
  • Replace swaps every copy of one piece of text for another.

Because each method returns a string, you can chain them: typed.Trim().ToUpper() trims, then uppercases the trimmed result.

Comparing without caring about case

== is exact, so "Kent" == "kent" is false. To ignore case, use Equals with StringComparison.OrdinalIgnoreCase:

string typedName = "kent";
Console.WriteLine(typedName == "Kent");
Console.WriteLine(typedName.Equals("Kent", StringComparison.OrdinalIgnoreCase));
False
True

Check yourself

2 questions to try on the lesson page.

So what

Find it, cut it, reshape it: IndexOf and friends tell you where things are, and Substring, Split and the rest turn messy text into the pieces you need.

Key terms

Cheat sheets