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.
Author by
Red Ranger
Updated on July 09, 2022Comments
-
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 about 9 yearsThanks m8. that's exactly what i was wanted to do.
-
schlebe almost 4 yearsYou can also add Dim ch As Char = s.Chars(3) '