CodeGym /Courses /C# SELF /Advanced string class methods

Advanced string class methods

C# SELF
Level 9, Lesson 4
Available

1. Searching for a substring in a string

In the last lecture, you learned how to get a substring from a string. Now let's learn how to find one string inside another. There are 5 awesome methods for this:

The Contains method: does the string contain a substring?

Returns true if the string you pass is found in the one you called the method on.

string phrase = "Wind of change";
bool hasWord = phrase.Contains("change"); // true
Checking for a substring using Contains

The search is case-sensitive! "wind".Contains("W") — false.

The IndexOf method: find the position of a substring

Works a lot like IndexOf in arrays: it searches for a substring in a string (from start to end) and returns the index of the first occurrence.

string text = "watermelonwatermelon";
int index = text.IndexOf("melon"); // 5
Finding the position of a substring using IndexOf
  • If nothing is found, it returns -1.
  • There's an alternative with a starting position: IndexOf("melon", 10). Just like with arrays.

The LastIndexOf method: last occurrence

Also works like LastIndexOf in arrays: it searches for a substring in a string (from end to start) and returns the index of the first occurrence from the end.

string repeated = "task task";
int last = repeated.LastIndexOf("task"); // 5
Finding the last occurrence of a substring using LastIndexOf

Does the string start/end with a given substring?

It's also common to check if our string starts (or ends) with a certain substring. There are two methods for this:

  • StartsWith — checks if the string starts with a certain substring;
  • EndsWith — checks if the string ends with a given substring.
string fileName = "photo.jpg";
bool isJpg = fileName.EndsWith(".jpg"); // true

string email = "support@company.com";
bool isSupport = email.StartsWith("support"); // true
Checking the start and end of a string

If you want to compare ignoring case, you need to pass an extra parameter specifying the comparison mode (see the docs for StringComparison.OrdinalIgnoreCase).

2. The Replace method: replacing characters and substrings

The Replace method replaces all occurrences of string A with string B. It was invented as a tool to fight typos, censorship, and replacing variables in templates! (Just kidding.)

string address = "London, Baker Street";
string updated = address.Replace("London", "Paris");
Console.WriteLine(updated); // "Paris, Baker Street"
Replacing a substring using Replace
  • You can even replace individual characters: str.Replace('a', 'z')
  • Important: all replacements happen throughout the whole string, not just the first occurrence.

3. The Split method: slicing a string into pieces

The Split method does this: it takes your string and chops it up using separators — characters or strings you want to split by. The method returns an array of strings that it cut from the original string.

string[] parts = originalString.Split(separator);
Syntax of the Split method
  • separator — a character or array of characters to use as the separator.

The simplest example

Let's split a string by space:

string input = "apple pear orange banana";
string[] fruits = input.Split(' '); 	// contains array ["apple","pear","orange","banana"]
Console.WriteLine(fruits[0]); 			// "apple"
Console.WriteLine(fruits[1]); 			// "pear"

Here we got an array of length 4, where each word is a separate element.

Multiple separators

Sometimes there might be more than one kind of separator in a string. For example, a user might enter values separated by spaces, commas, or semicolons.

In those cases, you can use an array of separator characters:

string input = "apple, pear; orange banana";
char[] separators = { ' ', ',', ';' };
string[] fruits = input.Split(separators, StringSplitOptions.RemoveEmptyEntries);

Bonus: the optional parameter StringSplitOptions.RemoveEmptyEntries removes empty fragments. This is handy if the user entered several separators in a row — like two spaces or something like "apple,, pear".

Splitting by substring

Separators can be strings, not just characters. For example, if you have a CSV file with a ";" or | separator:

// Separator by a single character
string data = "Ivanov;Petrov;Sidorov";
string[] names = data.Split(';'); // by character ';'

// Or, if the separator is a whole string:
string log = "2024-01-01::Error::Failed to complete task";
string[] separators = { "::" };
string[] parts = log.Split(separators);

4. The Join method: gluing an array of strings back together

The Join method does the opposite: it takes an array of strings and glues them into one string, inserting your chosen separator between the elements.

string result = string.Join(separator, arrayOfStrings);
Syntax of the Join method
  • separator — the string to insert between elements.
  • arrayOfStrings — an array or collection of strings (string[], List<string>, etc.).

The simplest example

Let's make one string from an array of strings, separated by commas:

string[] items = { "apple", "pear", "orange", "banana" };
string joined = string.Join(", ", items);
Console.WriteLine(joined); // "apple, pear, orange, banana"
Joining an array of strings using Join

Joining with an empty separator — merging strings into one

Sometimes you just want to glue strings together without putting anything between them:

string[] parts = { "I", "love", "C#" };
string message = string.Join("", parts);
Console.WriteLine(message); // "IloveC#"
Joining strings with no separator

5. Typical mistakes

A super common mistake for beginner devs is forgetting to trim extra spaces after splitting a string with Split. For example, if a user has shaky hands and types "apple, pear ,banana", after Split you'll get elements like " pear ". If you immediately convert to numbers or compare, you'll get a bug. Use Trim() after Split for each element — it's a good habit.

Another thing — extra empty strings. If the user entered two separators in a row or started/ended the string with a separator, Split might return empty elements. Turn on StringSplitOptions.RemoveEmptyEntries so you don't get errors later.

If the array for Join contains empty elements or null, Join will just ignore them. But if you don't want that (like, if it's important for a report to show that some values were skipped), you'll have to process the array manually first.

And one more thing: Split never changes the original string, it returns a new array. Join also doesn't change the original array, it gives you a new string. Remember: strings and arrays in C# are immutable (unchangeable).

2
Task
C# SELF, level 9, lesson 4
Locked
Replacing a substring in text using the `Replace` method
Replacing a substring in text using the `Replace` method
2
Task
C# SELF, level 9, lesson 4
Locked
Splitting a string into parts and joining them back together
Splitting a string into parts and joining them back together
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION