Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Trim and remove characters from strings in .NET

Feedback

In this article

If you're parsing a sentence into individual words, you might end up with words that have blank spaces (also called white spaces) on either end of the word. In this situation, you can use one of the trim methods in theSystem.String class to remove any number of spaces or other characters from a specified position in the string. The following table describes the available trim methods:

Method nameUse
String.TrimRemoves white spaces or characters specified in an array of characters from the beginning and end of a string.
String.TrimEndRemoves characters specified in an array of characters from the end of a string.
String.TrimStartRemoves characters specified in an array of characters from the beginning of a string.
String.RemoveRemoves a specified number of characters from a specified index position in a string.

Trim

You can easily remove white spaces from both ends of a string by using theString.Trim method, as shown in the following example:

string MyString = " Big   ";Console.WriteLine($"Hello{MyString}World!");string TrimString = MyString.Trim();Console.WriteLine($"Hello{TrimString}World!");//       The example displays the following output://             Hello Big   World!//             HelloBigWorld!
Dim MyString As String = " Big   "Console.WriteLine("Hello{0}World!", MyString)Dim TrimString As String = MyString.Trim()Console.WriteLine("Hello{0}World!", TrimString)' The example displays the following output:'       Hello Big   World!'       HelloBigWorld!

You can also remove characters that you specify in a character array from the beginning and end of a string. The following example removes white-space characters, periods, and asterisks:

using System;public class Example{   public static void Main()   {      String header = "* A Short String. *";      Console.WriteLine(header);      Console.WriteLine(header.Trim( new Char[] { ' ', '*', '.' } ));   }}// The example displays the following output://       * A Short String. *//       A Short String
Module Example    Public Sub Main()        Dim header As String = "* A Short String. *"        Console.WriteLine(header)        Console.WriteLine(header.Trim({" "c, "*"c, "."c}))    End SubEnd Module' The example displays the following output:'       * A Short String. *'       A Short String

TrimEnd

TheString.TrimEnd method removes characters from the end of a string, creating a new string object. An array of characters is passed to this method to specify the characters to be removed. The order of the elements in the character array doesn't affect the trim operation. The trim stops when a character not specified in the array is found.

The following example removes the last letters of a string using theTrimEnd method. In this example, the position of the'r' character and the'W' character are reversed to illustrate that the order of characters in the array doesn't matter. Notice that this code removes the last word ofMyString plus part of the first.

string MyString = "Hello World!";char[] MyChar = {'r','o','W','l','d','!',' '};string NewString = MyString.TrimEnd(MyChar);Console.WriteLine(NewString);
Dim MyString As String = "Hello World!"Dim MyChar() As Char = {"r", "o", "W", "l", "d", "!", " "}Dim NewString As String = MyString.TrimEnd(MyChar)Console.WriteLine(NewString)

This code displaysHe to the console.

The following example removes the last word of a string using theTrimEnd method. In this code, a comma follows the wordHello and because the comma isn't specified in the array of characters to trim, the trim ends at the comma.

string MyString = "Hello, World!";char[] MyChar = {'r','o','W','l','d','!',' '};string NewString = MyString.TrimEnd(MyChar);Console.WriteLine(NewString);
Dim MyString As String = "Hello, World!"Dim MyChar() As Char = {"r", "o", "W", "l", "d", "!", " "}Dim NewString As String = MyString.TrimEnd(MyChar)Console.WriteLine(NewString)

This code displaysHello, to the console.

TrimStart

TheString.TrimStart method is similar to theString.TrimEnd method except that it creates a new string by removing characters from the beginning of an existing string object. An array of characters is passed to theTrimStart method to specify the characters to be removed. As with theTrimEnd method, the order of the elements in the character array doesn't affect the trim operation. The trim stops when a character not specified in the array is found.

The following example removes the first word of a string. In this example, the position of the'l' character and the'H' character are reversed to illustrate that the order of characters in the array doesn't matter.

string MyString = "Hello World!";char[] MyChar = {'e', 'H','l','o',' ' };string NewString = MyString.TrimStart(MyChar);Console.WriteLine(NewString);
Dim MyString As String = "Hello World!"Dim MyChar() As Char = {"e", "H", "l", "o", " "}Dim NewString As String = MyString.TrimStart(MyChar)Console.WriteLine(NewString)

This code displaysWorld! to the console.

Remove

TheString.Remove method removes a specified number of characters that begin at a specified position in an existing string. This method assumes a zero-based index.

The following example removes 10 characters from a string beginning at position five of a zero-based index of the string.

string MyString = "Hello Beautiful World!";Console.WriteLine(MyString.Remove(5,10));// The example displays the following output://         Hello World!
Dim MyString As String = "Hello Beautiful World!"Console.WriteLine(MyString.Remove(5, 10))' The example displays the following output:'         Hello World!

Replace

You can also remove a specified character or substring from a string by calling theString.Replace(String, String) method and specifying an empty string (String.Empty) as the replacement. The following example removes all commas from a string:

using System;public class Example{   public static void Main()   {      String phrase = "a cold, dark night";      Console.WriteLine($"Before: {phrase}");      phrase = phrase.Replace(",", "");      Console.WriteLine($"After: {phrase}");   }}// The example displays the following output://       Before: a cold, dark night//       After: a cold dark night
Module Example    Public Sub Main()        Dim phrase As String = "a cold, dark night"        Console.WriteLine("Before: {0}", phrase)        phrase = phrase.Replace(",", "")        Console.WriteLine("After: {0}", phrase)    End SubEnd Module' The example displays the following output:'       Before: a cold, dark night'       After: a cold dark night
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?