vb.netvisual-studio-2012basic

How to get the charater at a specific position of a string in Visual Basic?


I want to get a character available at specific position in Visual Basic for example the string is "APPLE".

I want to get the 3rd character in the string which is "P".


Solution

  • You can look at a string as an array of Chars. The characters are indexed from 0 to the number of characters minus 1.

    ' For the 3rd character (the second P):
    
    Dim s As String = "APPLE"
    Dim ch As Char =  s(2) ' = "P"c,  where s(0) is "A"c
    

    Or

    Dim ch2 As Char = s.Chars(2) 'According to @schlebe's comment
    

    Or

    Dim substr As String = s.Substring(2, 1) 's.Substring(0, 1) is "A"
    

    Or

    Dim substr As String = Mid(s, 3, 1) 'Mid(s, 1, 1) is "A" (this is a relict from VB6)
    

    Note: The first two variants return a Char. The two others return a String of length 1. The Substring method is common to all .NET languages, where as the function Mid is VB specific and was introduced in order to facilitate the transition from VB6 to VB.NET.

    The indexer (array), Chars and Substring have a 0-based index, while Mid is 1-based which can be quite confusing.