VB.NET Trim String

This code snippet shows how to trim a string in VB.NET.
  • 7918

The String class provides Trim, TrimStart and TrimEnd methods to trim strings. The Trim method removes white spaces from the beginning and end of a string. The TrimEnd method removes characters specified in an array of characters from the end of a string and TrimStart method removes characters specified in an array of characters from the beginning of a string.

You can also use the Remove method to remove characters from a string. The Listing 2 code shows how to use these methods.

    Module Module1
        Sub Main()
            Dim str As [String] = " C# "
            Console.WriteLine("Hello{0}World!", str)
            Dim trStr As String = str.Trim()
            Console.WriteLine("Hello{0}World!", trStr)
            str =
"Hello World!"
            Dim chArr As Char() = {"e"c, "H"c, "l"c, "o"c, " "c}
            trStr = str.TrimStart(chArr)
            Console.WriteLine(trStr)
            str =
"Hello World!"
            Dim chArr1 As Char() = {"e"c, "H"c, "l"c, "o"c, " "c}
            trStr = str.TrimEnd(chArr1)
            Console.WriteLine(trStr)
            Dim MyString As String = "Hello Delta World!"
            Console.WriteLine(MyString.Remove(5, 10))
            Console.ReadLine()
        End Sub
    End
Module

Output

TR1.gif
 

Conclusion

Hope this article would have helped you in understanding Trim String in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.