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.
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.
C#1string sentence = "C# is fun!"; 2string[] words = sentence.Split(' '); // splitting by whitespace 3for (int i = 0; i < words.Length; i++) 4{ 5 Console.WriteLine(words[i]); // Output: "C#", "is", "fun!" 6}
In the example above, we observe that Split()
divides sentence
into words. We can also opt for different delimiters, such as a comma.
C#1string data = "John,Doe,35,Engineer"; 2string[] info = data.Split(','); // provided a ',' delimiter 3for (int i = 0; i < info.Length; i++) 4{ 5 Console.WriteLine(info[i]); // Output: "John", "Doe", "35", "Engineer" 6}
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:
C#1string[] words = { "Programming", "with", "C#", "is", "exciting!" }; 2string sentence = string.Join(" ", words); 3Console.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.
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:
C#1string name = " John Doe \t\n"; 2name = name.Trim(); 3Console.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:
C#1string name = " John Doe "; 2Console.WriteLine(name.TrimStart()); // Output: "John Doe " 3Console.WriteLine(name.TrimEnd()); // Output: " John Doe"
C#'s built-in type conversion functions, such as Convert.ToInt32()
, Convert.ToString()
, Convert.ToDouble()
, and Convert.ToBoolean()
, enable switching between different data types. The GetType()
method in C# returns the exact runtime type of the current instance.
C#1string numStr = "123"; 2Console.WriteLine(numStr.GetType()); // Output: System.String 3int num = Convert.ToInt32(numStr); 4Console.WriteLine(num.GetType()); // Output: System.Int32
We can use Convert.ToString()
to convert various types to a string, which can be handy for concatenating a string with a number:
C#1string name = "John"; 2int age = 25; 3Console.WriteLine("My name is " + name + ", and I am " + Convert.ToString(age) + " years old."); 4// Prints: My name is John, and I am 25 years old.
Let's look at other type conversions:
- Convert to double:
C#1string doubleStr = "123.45"; 2double doubleNum = Convert.ToDouble(doubleStr); 3Console.WriteLine(doubleNum.GetType()); // Output: System.Double
- Convert to boolean:
C#1string boolStr = "true"; 2bool boolValue = Convert.ToBoolean(boolStr); 3Console.WriteLine(boolValue.GetType()); // Output: System.Boolean
In specific scenarios, we need to combine all these methods. One such scenario could be the task of calculating the average of a string of numbers separated by commas:
C#1string numbers = " 1, 2, 3 ,4, 5 "; 2// Trim and Split the string to an array of numbers 3string[] trimmedNumbers = numbers.Trim().Split(','); 4for (int i = 0; i < trimmedNumbers.Length; i++) 5{ 6 trimmedNumbers[i] = trimmedNumbers[i].Trim(); // Trim each split part 7} 8 9// Convert string array to an array of integers 10int[] numArray = Array.ConvertAll(trimmedNumbers, int.Parse); 11for (int i = 0; i < numArray.Length; i++) 12{ 13 Console.WriteLine(numArray[i]); // Output: 1, 2, 3, 4, 5 14} 15 16// Calculate average 17double average = numArray.Average(); 18Console.WriteLine("The average is " + Convert.ToString(average)); // Output: The average is 3.0 19 20// Join the cleaned-up string array back into a single string 21string cleanedNumbers = string.Join(",", trimmedNumbers); 22Console.WriteLine("Cleaned numbers string: " + cleanedNumbers); // Output: Cleaned numbers string: 1,2,3,4,5
The ConvertAll
method in the above line converts an array of one type to an array of another type. It receives two parameters:
- The source array (in this case,
trimmedNumbers
which is an array of strings). - A
Converter<TInput, TOutput>
delegate that specifies the method used to convert each element (in this case,int.Parse
which converts each string to an integer).
By integrating these methods, we can transform the string 1, 2, 3 ,4, 5
into a cleaned-up array of numbers, calculate their average, and display the result, along with a joined version of the cleaned string.
Well done! A quick recap: C#'s Split()
, Join()
, Trim()
, and type conversion methods are fundamental functionalities in C# programming. Now, practice these concepts in the subsequent exercises. Happy programming!