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
- Remove part of a string by its position with Remove(start) and Remove(start, count)
Key takeaways
IndexOfandLastIndexOfgive the index of the first or last match, or-1if it isn't there;Contains,StartsWithandEndsWithanswertrueorfalse.Substring(start, length)takes a length, not an end position;Substring(start)takes everything to the end.Remove(start, count)andRemove(start)cut those same parts out.Splitcuts a string into an array at each separator, andstring.Joinglues an array's elements back together.Trim,ToUpper,ToLowerandReplaceeach return a new string, so you can chain them, as intyped.Trim().ToUpper().==is exact about case;EqualswithStringComparison.OrdinalIgnoreCaseignores 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
Trimremoves spaces (and tabs and new lines) from both ends.TrimStartandTrimEnddo one end only.ToUpperandToLowerchange the case of every letter.Replaceswaps 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.
Removing part by its position: Remove
Trim only takes spaces off the ends, and Replace needs to know what the text says. Sometimes you know where the part is, but not what's in it. The ticket scanner records when each fan came in as 2026-11-17 19:30, and the attendance report wants the date alone: the first 10 characters, whatever the time was. A fan's phone number arrives as +1 614-555-0182, and the stadium's texting system wants it without the country code, the first 3 characters.
Remove cuts characters out by their position and returns what's left:
string scannedAt = "2026-11-17 19:30";
string phone = "+1 614-555-0182";
Console.WriteLine(scannedAt.Remove(10));
Console.WriteLine(phone.Remove(0, 3));
2026-11-17
614-555-0182
Remove(start)removes everything from indexstartto the end: here, the space and the time, from index 10 on.Remove(start, count)removescountcharacters, starting at indexstart: here, 3 characters from index 0, the+1and its space.
Remove is Substring's mirror. Substring keeps a part, and Remove throws that part away: scannedAt.Remove(10) gives the same date as scannedAt.Substring(0, 10). As with Substring, the start is an index counted from 0, the second number is how many characters (not an end position), and a position past the end of the string stops the program with an ArgumentOutOfRangeException.
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
Do it: get the name part of a fan's email
The fan club's welcome page greets each new member by the part of their email address before the @. People type their addresses with extra spaces and random capitals, so the code tidies each one up first.
The method gets one value:
email: the address as the fan typed it, astring(" Vanessa.Jones@example.com ").
For example:
| Step | The text |
|---|---|
| As typed | " Vanessa.Jones@example.com " |
| The spaces at both ends removed | "Vanessa.Jones@example.com" |
The @ is at index 13, so the part before it is |
"Vanessa.Jones" |
| In small letters | "vanessa.jones" |
So EmailName(" Vanessa.Jones@example.com ") returns "vanessa.jones".
Your job: write the method EmailName(string email) so it returns the name part, a string.
- Remove the spaces at both ends.
- Keep only the text before the
@. - Change it to small (lowercase) letters.
- If the text has no
@, return""(an empty string).
Practiced live on the lesson page: write the C# right there and check it.
Do it: take the country code off a fan's phone number
The stadium texts fans when the gates open. Its texting system wants a US phone number without the country code, but some fans type the number with +1 in front and some don't.
The method gets one value:
phone: the phone number as the fan typed it, astring("+1 614-555-0182").
For example, "+1 614-555-0182":
| Index | 0 | 1 | 2 | 3 to 14 |
|---|---|---|---|---|
| Character | + |
1 |
a space | 614-555-0182 |
| Removed? | yes | yes | yes | no |
So LocalNumber("+1 614-555-0182") returns "614-555-0182".
Your job: write the method LocalNumber(string phone) so it returns the number, a string, without the country code.
- When
phonestarts with+1(a plus, a one and a space), remove those 3 characters withRemove, and return what's left. - When it doesn't, return
phoneas it is:LocalNumber("614-555-0182")returns"614-555-0182".
Practiced live on the lesson page: write the C# right there and check it.
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.