📅  最后修改于: 2023-12-03 14:47:43.739000             🧑  作者: Mango
The Trim()
method in C# is used to remove all leading and trailing white-space characters from a string and returns a new string. It does not modify the original string.
The syntax for Trim()
method is as follows:
public string Trim();
string myString = " Hello, World! ";
string trimmedString = myString.Trim();
Console.WriteLine(trimmedString); // Output: "Hello, World!"
In the above example, the Trim()
method is called on the myString
string variable, which contains leading and trailing white-space characters. The method returns a new string with all the leading and trailing white-space characters removed and assigns it to the trimmedString
variable.
Finally, the Console.WriteLine()
method is used to print the trimmedString
variable.
Trim()
method will remove all the leading and trailing white-space characters, including newline, tab, and other whitespace characters.Trim()
method is case-sensitive; it will not remove whitespace characters that are in the middle of the string.null
, the Trim()
method will throw a NullReferenceException
.The Trim()
method is a useful string method in C# that is used to remove leading and trailing white-space characters from a string. It is a simple and straightforward method that can be used to clean up strings before processing them in your application.