C# String Trim() Method

https:/‮www/‬.theitroad.com

The Trim() method in C# is used to remove any leading or trailing whitespace characters from a string. It returns a new string with the whitespace characters removed.

The syntax of the Trim() method is as follows:

string trimmedString = string.Trim();

For example, to remove leading and trailing whitespace from a string, you can use the following code:

string text = "  Hello World  ";
string trimmedText = text.Trim();
Console.WriteLine(trimmedText);  // Output: "Hello World"

In this example, the Trim() method is used to remove the leading and trailing spaces from the string " Hello World ". The resulting string "Hello World" is assigned to the trimmedText variable, which is then printed to the console using the WriteLine() method.

Note that the Trim() method does not modify the original string. Instead, it returns a new string with the whitespace characters removed. If you need to modify the original string, you can assign the result of the Trim() method back to the original string variable. Additionally, there are several other versions of the Trim() method, such as TrimStart() and TrimEnd(), which remove whitespace characters from only the beginning or end of the string, respectively.