Lesson Overview

Greetings! In this lesson, we'll explore C#'s string methods: Split(), Join(), Trim(), and learn how to perform type conversions. C#'s robust built-in string methods simplify text processing, enhancing the readability and efficiency of our code.

Understanding C#'s Split() Method

Constructing strings frequently entails dividing them into smaller sections or 'tokens.' The Split() method in C# achieves this goal by breaking a string into an array of substrings using a specified delimiter. If no delimiter is provided, it splits the string by a single whitespace character.

string sentence = "C# is fun!";
string[] words = sentence.Split(' '); // splitting by whitespace
for (int i = 0; i < words.Length; i++)
{
    Console.WriteLine(words[i]);  // Output: "C#", "is", "fun!"
}

In the example above, we observe that Split() divides sentence into words. We can also opt for different delimiters, such as a comma.

string data = "John,Doe,35,Engineer";
string[] info = data.Split(','); // provided a ',' delimiter
for (int i = 0; i < info.Length; i++)
{
    Console.WriteLine(info[i]);  // Output: "John", "Doe", "35", "Engineer"
}
Exploring the Join() Method

Conversely, C#'s Join() method concatenates, or 'joins,' strings into a single string. The first parameter of Join() is the delimiter that will be used to separate the strings in the resulting single string:

string[] words = { "Programming", "with", "C#", "is", "exciting!" };
string sentence = string.Join(" ", words);
Console.WriteLine(sentence);  // Output: "Programming with C# is exciting!"

Here, Join() takes an array of words, which are strings, and merges them into a sentence — a single string, using a space as a delimiter.

Mastering the Trim() Method

Discerning extra spaces in strings can prove challenging, and they may lead to problems. C#'s Trim() method removes leading and trailing spaces, tab, or newline characters from a string:

string name = "    John Doe    \t\n";
name = name.Trim();
Console.WriteLine(name);  // Output: "John Doe"

Furthermore, we can use TrimStart() and TrimEnd() to remove spaces, tabs, and newline characters from the left and right of a string, respectively:

string name = "    John Doe    ";
Console.WriteLine(name.TrimStart());  // Output: "John Doe    "
Console.WriteLine(name.TrimEnd());  // Output: "    John Doe"
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal