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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:08:53  来源:igfitidea点击:

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

vb.netvisual-studio-2012basic

提问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 Stringof length 1. The common .NET way available in all the languages is to use the method Substring, where as the function Midis 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~