在字符串中查找字符的位置 [英] Finding locations of a char in a string

查看:54
本文介绍了在字符串中查找字符的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取字符串中某些字符的位置?

How can I get the position of certain characters in a string?

示例:my string = "你好,你在做什么"

Example: my string = "hello, what you doing"

并且我想从那些应该返回位置编号 4、13 和 13 的字符串中返回 o 的位置.17. 我试过 str.IndexOf 但它只返回第一次出现的 o.

and I would like to return the position of o from those string which should return me position numbers 4, 13 & 17. I've tried str.IndexOf but it only returns the first occurrence of o.

这是我尝试过的:

    Dim str = "hello, what you doing"
    Dim dIndex = str.IndexOf("o")
    If (dIndex > -1) Then
        Console.WriteLine(dIndex.toString())
    End If

任何方法都可以.

我使用的是 Visual Studio 2008.

I am using Visual Studio 2008.

推荐答案

有一个 IndexOf 的重载,它占据了开始寻找的位置.

There is an overload of IndexOf which takes the position to start looking from.

因此,一旦您找到第一个匹配字符的位置,您就可以告诉它从该位置之后继续查找.

So once you have found the position of the first matching character, you can tell it to carry on looking starting just after that position.

这里我做了一个函数,它返回一个位置列表.(如果没有匹配项,则列表将为空.)

Here I made a function which returns a list of the positions. (If there are no matches then the list will be empty.)

Option Strict On
Option Infer On

Module Module1

    Function IndexesOf(s As String, c As Char) As List(Of Integer)
        Dim positions As New List(Of Integer)
        Dim pos = s.IndexOf(c)
        While pos >= 0
            positions.Add(pos)
            pos = s.IndexOf(c, pos + 1)
        End While

        Return positions

    End Function

    Sub Main()
        Dim os = IndexesOf("hello, what you doing", "o"c)
        For Each pos In os
            Console.WriteLine(pos)
        Next

        Console.ReadLine()

    End Sub

End Module

输出:

4
13
17

4
13
17

这篇关于在字符串中查找字符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆