获得焦炭的第n个指标在一个字符串 [英] Get index of nth occurrence of char in a string

查看:121
本文介绍了获得焦炭的第n个指标在一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个函数,返回一个字符串指定字符的第N次出现的索引。

I'm trying to make a function that returns the index of the Nth occurrence of a given char in a string.

下面是我的尝试:

private int IndexOfNth(string str, char c, int n)
{
    int index = str.IndexOf(c) + 1;
    if (index >= 0)
    {
        string temp = str.Substring(index, str.Length - index);
        for (int j = 1; j < n; j++)
        {
            index = temp.IndexOf(c) + 1;
            if (index < 0)
            {
                return -1;
            }
            temp = temp.Substring(index, temp.Length - index);
        }
        index = index + (str.Length);
    }
    return index;
}

本的的发现第一次出现,砍掉该字符串的前部,找到来自新子第一次出现,和和,直到它得到的第n次出现的索引。不过,我没有考虑到如何最终字符串的索引将被从原来的字符串原实际指数所抵消。我如何使这项工作?

This should find the first occurrence, chop off that front part of the string, find the first occurrence from the new substring, and on and on until it gets the index of the nth occurrence. However I failed to consider how the index of the final substring is going to be offset from the original actual index in the original string. How do I make this work?

另外,作为一个侧面的问题,如果我想的字符是制表符我通过这个功能'\ t'或什么?

Also as a side question, if I want the char to be the tab character do I pass this function '\t' or what?

推荐答案

使用LINQ找到第5'的指数 A 在字符串中的 aababaababa

Using LINQ to find the index of the 5'th a in the string aababaababa:

var str = "aababaababa";
var ch = 'a';
var n = 5;
var result = str
  .Select((c, i) => new { c, i })
  .Where(x => x.c == ch)
  .Skip(n - 1)
  .FirstOrDefault();
return result != null ? result.i : -1;

这篇关于获得焦炭的第n个指标在一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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