String Functions in Visual Basic .NET

The standard library’s String class provides many useful string-related functions. Here are some examples to give you a sense of the functionality available.

Imports System

Module StringFunctions
    ' We alias Console.WriteLine to a shorter name as we'll use it a lot below.
    Private p As Action(Of Object) = AddressOf Console.WriteLine

    Sub Main()
        ' Here's a sample of the functions available for string manipulation.
        ' In VB.NET, these are methods on the String object itself or static
        ' methods of the String class. You can find more functions in the
        ' String class documentation.

        p("Contains:  " & "test".Contains("es"))
        p("Count:     " & "test".Count(Function(c) c = "t"c))
        p("StartsWith: " & "test".StartsWith("te"))
        p("EndsWith:  " & "test".EndsWith("st"))
        p("IndexOf:   " & "test".IndexOf("e"))
        p("Join:      " & String.Join("-", {"a", "b"}))
        p("Repeat:    " & String.Concat(Enumerable.Repeat("a", 5)))
        p("Replace:   " & "foo".Replace("o", "0"))
        p("Replace:   " & "foo".Replace("o", "0", 1, StringComparison.Ordinal))
        p("Split:     " & String.Join(", ", "a-b-c-d-e".Split("-"c)))
        p("ToLower:   " & "TEST".ToLower())
        p("ToUpper:   " & "test".ToUpper())
    End Sub
End Module

To run the program, save it as StringFunctions.vb and use the VB.NET compiler:

$ vbc StringFunctions.vb
$ mono StringFunctions.exe
Contains:  True
Count:     2
StartsWith: True
EndsWith:  True
IndexOf:   1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     a, b, c, d, e
ToLower:   test
ToUpper:   TEST

This example demonstrates various string manipulation methods in Visual Basic .NET. Note that some functions have slightly different names or implementations compared to other languages, but they provide similar functionality. For instance, HasPrefix and HasSuffix in some languages are equivalent to StartsWith and EndsWith in VB.NET.

The String class in VB.NET provides a rich set of methods for string manipulation, and the Enumerable class (part of LINQ) offers additional functionality for working with sequences of characters or strings.