📜  string trin c# (1)

📅  最后修改于: 2023-12-03 14:47:43.739000             🧑  作者: Mango

String.Trim() Method in C#

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.

Syntax

The syntax for Trim() method is as follows:

public string Trim();
Example
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.

Remarks
  • The Trim() method will remove all the leading and trailing white-space characters, including newline, tab, and other whitespace characters.
  • The Trim() method is case-sensitive; it will not remove whitespace characters that are in the middle of the string.
  • If the string is null, the Trim() method will throw a NullReferenceException.
Conclusion

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.