Bewerken

Share via


String.Trim Method

Definition

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.

Overloads

Trim(Char)

Removes all leading and trailing instances of a character from the current string.

Trim(ReadOnlySpan<Char>)

Removes all leading and trailing occurrences of a set of characters specified in a span from the current string.

Trim()

Removes all leading and trailing white-space characters from the current string.

Trim(Char[])

Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

Trim(Char)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Removes all leading and trailing instances of a character from the current string.

public:
 System::String ^ Trim(char trimChar);
public string Trim (char trimChar);
member this.Trim : char -> string
Public Function Trim (trimChar As Char) As String

Parameters

trimChar
Char

A Unicode character to remove.

Returns

The string that remains after all instances of the trimChar character are removed from the start and end of the current string. If no characters can be trimmed from the current instance, the method returns the current instance unchanged.

Remarks

The Trim(System.Char) method removes from the current string all leading and trailing instances of the trimChar character. Each leading and trailing trim operation stops when a character different from trimChar is encountered. For example, if trimChar is - and the current string is "---abc---xyz----", the Trim(System.Char) method returns "abc---xyz". To remove characters between words in a string, use .NET Regular Expressions.

Note

If the Trim(System.Char) method removes any characters from the current instance, this method does not modify the value of the current instance. Instead, it returns a new string in which all leading and trailing trimChar characters found in the current instance are removed.

If the current string equals Empty or all the characters in the current instance consist of trimChar characters, the method returns Empty.

Applies to

Trim(ReadOnlySpan<Char>)

Removes all leading and trailing occurrences of a set of characters specified in a span from the current string.

public:
 System::String ^ Trim(ReadOnlySpan<char> trimChars);
public string Trim (scoped ReadOnlySpan<char> trimChars);
member this.Trim : ReadOnlySpan<char> -> string
Public Function Trim (trimChars As ReadOnlySpan(Of Char)) As String

Parameters

trimChars
ReadOnlySpan<Char>

A span of Unicode characters to remove.

Returns

The string that remains after all occurrences of the characters in the trimChars parameter are removed from the start and end of the current string. If trimChars is empty, white-space characters are removed instead. If no characters can be trimmed from the current instance, the method returns the current instance unchanged.

Applies to

Trim()

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Removes all leading and trailing white-space characters from the current string.

public:
 System::String ^ Trim();
public string Trim ();
member this.Trim : unit -> string
Public Function Trim () As String

Returns

The string that remains after all white-space characters are removed from the start and end of the current string. If no characters can be trimmed from the current instance, the method returns the current instance unchanged.

Examples

The following example uses the String.Trim() method to remove any extra white space from strings entered by the user before concatenating them.

using namespace System;

void main()
{
   Console::Write("Enter your first name: ");
   String^ firstName = Console::ReadLine();
   
   Console::Write("Enter your middle name or initial: ");
   String^ middleName = Console::ReadLine();
   
   Console::Write("Enter your last name: ");
   String^ lastName = Console::ReadLine();
   
   Console::WriteLine();
   Console::WriteLine("You entered '{0}', '{1}', and '{2}'.",
                      firstName, middleName, lastName);
   
   String^ name = ((firstName->Trim() + " " + middleName->Trim())->Trim() + " " +
                  lastName->Trim())->Trim();
   Console::WriteLine("The result is " + name + ".");
}
// The following is possible output from this example:
//       Enter your first name:    John
//       Enter your middle name or initial:
//       Enter your last name:    Doe
//       
//       You entered '   John  ', '', and '   Doe'.
//       The result is John Doe.
using System;

public class Example
{
    public static void Main()
    {
        Console.Write("Enter your first name: ");
        string firstName = Console.ReadLine();
      
        Console.Write("Enter your middle name or initial: ");
        string middleName = Console.ReadLine();
      
        Console.Write("Enter your last name: ");
        string lastName = Console.ReadLine();
      
        Console.WriteLine();
        Console.WriteLine("You entered '{0}', '{1}', and '{2}'.", 
                        firstName, middleName, lastName);
      
        string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " + 
                    lastName.Trim()).Trim();
        Console.WriteLine("The result is " + name + ".");

        // The following is a possible output from this example:
        //       Enter your first name:    John
        //       Enter your middle name or initial:
        //       Enter your last name:    Doe
        //       
        //       You entered '   John  ', '', and '   Doe'.
        //       The result is John Doe.
    }
}
printf "Enter your first name: "
let firstName = stdin.ReadLine()

printf "Enter your middle name or initial: "
let middleName = stdin.ReadLine()

printf "Enter your last name: "
let lastName = stdin.ReadLine()

printfn $"\nYou entered '{firstName}', '{middleName}', and '{lastName}'." 

let name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " + lastName.Trim()).Trim()
printfn $"The result is {name}."

// The following is a possible output from this example:
//       Enter your first name:    John
//       Enter your middle name or initial:
//       Enter your last name:    Doe
//       
//       You entered '   John  ', '', and '   Doe'.
//       The result is John Doe.
Module Example
   Public Sub Main()
      Console.Write("Enter your first name: ")
      Dim firstName As String = Console.ReadLine()
      
      Console.Write("Enter your middle name or initial: ")
      Dim middleName As String = Console.ReadLine()
      
      Console.Write("Enter your last name: ")
      Dim lastName As String = Console.ReadLine
      
      Console.WriteLine()
      Console.WriteLine("You entered '{0}', '{1}', and '{2}'.", _
                        firstName, middleName, lastName)
                        
      Dim name As String = ((firstName.Trim() + " " + middleName.Trim()).Trim() _
                           + " " + lastName.Trim()).Trim()                        
      Console.WriteLine("The result is " + name + ".")
   End Sub
End Module
' The following is possible output from this example:
'       Enter your first name:    John
'       Enter your middle name or initial:
'       Enter your last name:    Doe
'       
'       You entered '   John  ', '', and '   Doe'.
'       The result is John Doe.

Remarks

The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz". To remove white-space characters between words in a string, use .NET Regular Expressions.

Note

If the Trim method removes any characters from the current instance, this method does not modify the value of the current instance. Instead, it returns a new string in which all leading and trailing white space characters found in the current instance are removed.

If the current string equals Empty or all the characters in the current instance consist of white-space characters, the method returns Empty.

White-space characters are defined by the Unicode standard. The Trim method removes any leading and trailing characters that produce a return value of true when they are passed to the Char.IsWhiteSpace method.

Notes to Callers

The .NET Framework 3.5 SP1 and earlier versions maintain an internal list of white-space characters that this method trims. Starting with the .NET Framework 4, the method trims all Unicode white-space characters (that is, characters that produce a true return value when they are passed to the IsWhiteSpace(Char) method). Because of this change, the Trim() method in the .NET Framework 3.5 SP1 and earlier versions removes two characters, ZERO WIDTH SPACE (U+200B) and ZERO WIDTH NO-BREAK SPACE (U+FEFF), that the Trim() method in the .NET Framework 4 and later versions does not remove. In addition, the Trim() method in the .NET Framework 3.5 SP1 and earlier versions does not trim three Unicode white-space characters: MONGOLIAN VOWEL SEPARATOR (U+180E), NARROW NO-BREAK SPACE (U+202F), and MEDIUM MATHEMATICAL SPACE (U+205F).

See also

Applies to

Trim(Char[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

public:
 System::String ^ Trim(... cli::array <char> ^ trimChars);
public string Trim (params char[] trimChars);
public string Trim (params char[]? trimChars);
member this.Trim : char[] -> string
Public Function Trim (ParamArray trimChars As Char()) As String

Parameters

trimChars
Char[]

An array of Unicode characters to remove, or null.

Returns

The string that remains after all occurrences of the characters in the trimChars parameter are removed from the start and end of the current string. If trimChars is null or an empty array, white-space characters are removed instead. If no characters can be trimmed from the current instance, the method returns the current instance unchanged.

Examples

The following example uses the Trim(System.Char[]) method to remove space, asterisk (*), and apostrophe (') characters from a string.

using namespace System;

void main()
{
   array<Char>^ charsToTrim = { L'*', L' ', L'\\' };
   String^ banner = "*** Much Ado About Nothing ***";
   String^ result = banner->Trim(charsToTrim);
   Console::WriteLine("Trimmmed\n   {0}\nto\n   '{1}'", banner, result);
}
// The example displays the following output:
//       Trimmmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'
char[] charsToTrim = { '*', ' ', '\''};
string banner = "*** Much Ado About Nothing ***";
string result = banner.Trim(charsToTrim);
Console.WriteLine("Trimmed\n   {0}\nto\n   '{1}'", banner, result);

// The example displays the following output:
//       Trimmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'
let charsToTrim = [| '*'; ' '; '\'' |]
let banner = "*** Much Ado About Nothing ***"
let result = banner.Trim charsToTrim
printfn $"Trimmmed\n   {banner}\nto\n   '{result}'"

// The example displays the following output:
//       Trimmmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'
Module Example
   Public Sub Main()
      Dim charsToTrim() As Char = { "*"c, " "c, "'"c}
      Dim banner As String = "*** Much Ado About Nothing ***"
      Dim result As String = banner.Trim(charsToTrim)
      Console.WriteLine("Trimmmed{0}   {1}{0}to{0}   '{2}'", _
                        vbCrLf, banner, result)
   End Sub
End Module
' The example displays the following output:
'       Trimmmed
'          *** Much Ado About Nothing ***
'       to
'          'Much Ado About Nothing'

Remarks

The Trim(System.Char[]) method removes from the current string all leading and trailing characters that are in the trimChars parameter. Each leading and trailing trim operation stops when a character that is not in trimChars is encountered. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the Trim(System.Char[]) method returns "abc456xyz".

Note

If the Trim(System.Char[]) method removes any characters from the current instance, this method does not modify the value of the current instance. Instead, it returns a new string in which all leading and trailing trimChars characters found in the current instance are removed.

If the current string equals Empty or all the characters in the current instance consist of characters in the trimChars array, the method returns Empty.

If trimChars is null or an empty array, this method removes any leading or trailing characters that result in the method returning true when they are passed to the Char.IsWhiteSpace method.

Notes to Callers

The .NET Framework 3.5 SP1 and earlier versions maintains an internal list of white-space characters that this method trims if trimChars is null or an empty array. Starting with the .NET Framework 4, if trimChars is null or an empty array, the method trims all Unicode white-space characters (that is, characters that produce a true return value when they are passed to the IsWhiteSpace(Char) method). Because of this change, the Trim() method in the .NET Framework 3.5 SP1 and earlier versions removes two characters, ZERO WIDTH SPACE (U+200B) and ZERO WIDTH NO-BREAK SPACE (U+FEFF), that the Trim() method in the .NET Framework 4and later versions does not remove. In addition, the Trim() method in the .NET Framework 3.5 SP1 and earlier versions does not trim three Unicode white-space characters: MONGOLIAN VOWEL SEPARATOR (U+180E), NARROW NO-BREAK SPACE (U+202F), and MEDIUM MATHEMATICAL SPACE (U+205F).

See also

Applies to