vb.net 如何在 Visual Basic 中获取字符串特定位置的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29062734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the charater at a specific position of a string in Visual Basic?
提问by Red Ranger
I want to get a character available at specific position in Visual Basic for example the string is "APPLE".
我想在 Visual Basic 中的特定位置获得一个可用的字符,例如字符串是“APPLE”。
I want to get the 3rd character in the string which is "P".
我想获取字符串中的第三个字符,即“P”。
回答by Olivier Jacot-Descombes
You can look at a string as an array of Chars. In this case the characters a numbered from 0 to number of characters minus 1.
您可以将字符串视为字符数组。在这种情况下,字符 a 编号从 0 到字符数减 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.
注意:如果你想返回一个Char
. 其他两个返回String
长度为 1 的a 。在所有语言中可用的通用 .NET 方式是使用 method Substring
,因为该函数Mid
是特定于 VB 的,并且是为了促进从 VB6 到 VB.NET 的过渡而引入的。
回答by ?ình ??c Nguy?n
You also can get a char in a string by index of this char.
您还可以通过该字符的索引获取字符串中的字符。
Dim s As String = "APPLE"
Dim c As Char = GetChar(s,4) ' = 'L' index = 1~