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

34,346

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',  where s(0) is "A"

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: Use the first variant if you want to return a Char. The two others return a String of length 1. The common .NET way available in all the languages is to use the method Substring, where as the function Mid is VB specific and was introduced in order to facilitate the transition from VB6 to VB.NET.

Share:
34,346
Red Ranger
Author by

Red Ranger

Updated on July 09, 2022

Comments

  • Red Ranger
    Red Ranger almost 2 years

    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".

  • Red Ranger
    Red Ranger about 9 years
    Thanks m8. that's exactly what i was wanted to do.
  • schlebe
    schlebe almost 4 years
    You can also add Dim ch As Char = s.Chars(3) '