查找字符的第N次出现在一个字符串 [英] Find Nth occurrence of a character in a string

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

问题描述

我需要创建返回字符的第N次出现的索引字符串中的C#方法帮助。

例如,在字符串中的字符'T' 3日发生dtststxtu 5。结果
(请注意,字符串有4 T 秒)


解决方案

 公众诠释GetNthIndex(字符串s,字符T,INT N)
{
    诠释计数= 0;
    的for(int i = 0; I< s.Length;我++)
    {
        如果(S [I] == T)
        {
            算上++;
            如果(计数== N)
            {
                返回我;
            }
        }
    }
    返回-1;
}

这是可以做了很多更清洁,并有输入没有检查。

I need help with creating a C# method that returns the index of the Nth occurrence of a character in a string.

For instance, the 3rd occurrence of the character 't' in the string "dtststxtu" is 5.
(Note that the string has 4 ts.)

解决方案

public int GetNthIndex(string s, char t, int n)
{
    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == t)
        {
            count++;
            if (count == n)
            {
                return i;
            }
        }
    }
    return -1;
}

That could be made a lot cleaner, and there are no checks on the input.

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

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