string 在字符串中查找字符的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7134100/
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
Find the index of a char in string?
提问by Voldemort
I have a string that goes like "abcdefg..."
我有一个像这样的字符串 "abcdefg..."
I would like to find the index where the letter dis at, so I can get the number 3.
我想找到字母d所在的索引,所以我可以得到数字3。
I managed to do it by looping through each letter in the string, but that doesn't sound very convenient. Is there another way?
我设法通过遍历字符串中的每个字母来做到这一点,但这听起来不太方便。还有其他方法吗?
回答by Grant Thomas
The String
class exposes some methods to enable this, such as IndexOf
and LastIndexOf
, so that you may do this:
本String
类暴露了一些方法来实现这一目标,如IndexOf
和LastIndexOf
,这样你可以这样做:
Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then
End If
回答by Carmelo La Monica
Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.
如果使用当前字母的方法会出现Contanis,并使用IndexOf方法存储相应的数字,请参见下面的示例。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains("d") Then
numberString = myString.IndexOf("d")
End If
End Sub
Another sample with TextBox
另一个带有 TextBox 的示例
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains(me.TextBox1.Text) Then
numberString = myString.IndexOf(Me.TextBox1.Text)
End If
End Sub
Regards
问候
回答by Adithya Surampudi
"abcdefgh..".IndexOf("d")
returns 3
返回 3
In general returns first occurrence index, if not present returns -1
一般返回第一次出现的索引,如果不存在返回-1