C# Trim Function Explained: Remove Spaces Fast
The function Trim() in C# is used to remove any leading or trailing spaces or specified characters from a string. It returns a new string that is the result of removing the specified characters from the beginning and end of the original string.
For example, if we have a string variable str with a value of “hello world”, we can use the Trim() function to remove leading and trailing spaces as shown below:
string str = " hello world ";
string trimmedStr = str.Trim();
Console.WriteLine(trimmedStr); // 输出:"hello world"
In addition to the default white space characters, we can also pass a character array or a character set as a parameter to remove specified characters from the beginning and end of a string. For example, we can use the Trim() function to remove the ‘!’ character from the beginning and end of a string, as shown below:
string str = "!!hello world!!";
char[] charsToTrim = { '!' };
string trimmedStr = str.Trim(charsToTrim);
Console.WriteLine(trimmedStr); // 输出:"hello world"
It is important to note that the Trim() function does not modify the original string, but instead returns a new string. If you want to modify the original string, use the TrimStart() and TrimEnd() functions.