Find Nth occurrence of a character in a string












69















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.)










share|improve this question

























  • What do you have to work with so far?

    – Anthony Forloney
    Apr 3 '10 at 15:48






  • 2





    I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

    – Lasse Vågsæther Karlsen
    Apr 3 '10 at 16:04
















69















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.)










share|improve this question

























  • What do you have to work with so far?

    – Anthony Forloney
    Apr 3 '10 at 15:48






  • 2





    I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

    – Lasse Vågsæther Karlsen
    Apr 3 '10 at 16:04














69












69








69


17






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.)










share|improve this question
















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.)







c# string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '13 at 21:10









ANeves

4,77712857




4,77712857










asked Apr 3 '10 at 15:44









jozijozi

1,34551937




1,34551937













  • What do you have to work with so far?

    – Anthony Forloney
    Apr 3 '10 at 15:48






  • 2





    I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

    – Lasse Vågsæther Karlsen
    Apr 3 '10 at 16:04



















  • What do you have to work with so far?

    – Anthony Forloney
    Apr 3 '10 at 15:48






  • 2





    I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

    – Lasse Vågsæther Karlsen
    Apr 3 '10 at 16:04

















What do you have to work with so far?

– Anthony Forloney
Apr 3 '10 at 15:48





What do you have to work with so far?

– Anthony Forloney
Apr 3 '10 at 15:48




2




2





I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

– Lasse Vågsæther Karlsen
Apr 3 '10 at 16:04





I have edited your answer to more clearly convey what you want. Hopefully you will get some answers that fit the question. Not being fluent in english is not a problem on Stack Overflow, you can always just add a line asking someone more fluent to edit your question and clean it up, but you must yourself strive to provide some examples in the question so that people understand what you need.

– Lasse Vågsæther Karlsen
Apr 3 '10 at 16:04












21 Answers
21






active

oldest

votes


















71














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.






share|improve this answer





















  • 5





    Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

    – Mike
    Feb 22 '14 at 15:57






  • 1





    love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

    – user734028
    Jan 8 '18 at 6:18



















18














There is a minor bug in previous solution.



Here is some updated code:



s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();





share|improve this answer





















  • 1





    What does it return if the character is not found?

    – Timuçin
    Sep 29 '14 at 10:53











  • It returns the length/count of the string s. You need to check for that value.

    – Yoky
    Nov 12 '15 at 0:34



















12














Update: Index of Nth occurance one-liner:



int NthOccurence(string s, char t, int n)
{
s.TakeWhile(c => n - (c == t)?1:0 > 0).Count();
}




Use these at your own risk. This looks like homework, so I left a few bugs in there for your to find:



int CountChars(string s, char t)
{
int count = 0;
foreach (char c in s)
if (s.Equals(t)) count ++;
return count;
}


.



int CountChars(string s, char t)
{
return s.Length - s.Replace(t.ToString(), "").Length;
}


.



int CountChars(string s, char t)
{
Regex r = new Regex("[\" + t + "]");
return r.Match(s).Count;
}





share|improve this answer





















  • 2





    Your one-liner example doesn't work because the value of n is never changed.

    – Dave Neeley
    Jun 3 '11 at 18:17






  • 2





    Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

    – nullable
    Oct 26 '11 at 20:15








  • 1





    −1, "so I left a few bugs in there for your to find"

    – Zanon
    Jan 9 '18 at 13:40



















8














Here's another LINQ solution:



string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char
var result = input.Select((c, i) => new { Char = c, Index = i })
.Where(item => item.Char == searchChar)
.Skip(occurrencePosition - 1)
.FirstOrDefault();

if (result != null)
{
Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
occurrencePosition, searchChar, result.Index);
}
else
{
Console.WriteLine("Position {0} of '{1}' not found!",
occurrencePosition, searchChar);
}




Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.



string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char

Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
.Cast<Match>()
.Skip(occurrencePosition - 1)
.FirstOrDefault();

if (match != null)
Console.WriteLine("Index: " + match.Index);
else
Console.WriteLine("Match not found!");





share|improve this answer

































    8














    Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):



    public static int IndexOfNth(
    this string input, string value, int startIndex, int nth)
    {
    if (nth < 1)
    throw new NotSupportedException("Param 'nth' must be greater than 0!");
    if (nth == 1)
    return input.IndexOf(value, startIndex);

    return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
    }


    Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):



    [Test]
    public void TestIndexOfNthWorksForNth1()
    {
    const string input = "foo<br />bar<br />baz<br />";
    Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
    }

    [Test]
    public void TestIndexOfNthWorksForNth2()
    {
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
    Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
    }

    [Test]
    public void TestIndexOfNthWorksForNth3()
    {
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
    Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
    }





    share|improve this answer

































      4














      Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:



      yourString.Where(c => c == 't').Count();





      share|improve this answer



















      • 2





        @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

        – Mike Two
        Apr 3 '10 at 16:04






      • 9





        Won't this just find how many occurrences of a character there are rather than the index of the nth one?

        – dx_over_dt
        Jun 26 '15 at 16:21



















      4














      ranomore correctly commented that Joel Coehoorn's one-liner doesn't work.



      Here is a two-liner that does work, a string extension method that returns the 0-based index of the nth occurrence of a character, or -1 if no nth occurrence exists:



      public static class StringExtensions
      {
      public static int NthIndexOf(this string s, char c, int n)
      {
      var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count();
      return takeCount == s.Length ? -1 : takeCount;
      }
      }





      share|improve this answer































        3














        Here is a fun way to do it



             int i = 0;
        string s="asdasdasd";
        int n = 3;
        s.Where(b => (b == 'd') && (i++ == n));
        return i;





        share|improve this answer































          3














          string result = "i am 'bansal.vks@gmail.com'"; // string

          int in1 = result.IndexOf('''); // get the index of first quote

          int in2 = result.IndexOf(''', in1 + 1); // get the index of second

          string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes





          share|improve this answer

































            3














            I add another answer that run pretty fast compared to others methods



            private static int IndexOfNth(string str, char c, int nth, int startPosition = 0)
            {
            int index = str.IndexOf(c, startPosition);
            if (index >= 0 && nth > 1)
            {
            return IndexOfNth(str, c, nth - 1, index + 1);
            }

            return index;
            }





            share|improve this answer































              2














              you can do this work with Regular Expressions.



                      string input = "dtststx";
              char searching_char = 't';
              int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index;


              best regard.






              share|improve this answer































                2














                public int GetNthOccurrenceOfChar(string s, char c, int occ)
                {
                return String.Join(c.ToString(), s.Split(new char { c }, StringSplitOptions.None).Take(occ)).Length;
                }





                share|improve this answer































                  2














                  if your interested you can also create string extension methods like so:



                       public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
                  {
                  //returns the placement of a string in another string
                  int num = 0;
                  int currentInst = 0;
                  //if optional argument, case sensitive is false convert string and marker to lowercase
                  if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
                  int myReturnValue = -1; //if nothing is found the returned integer is negative 1
                  while ((num + yourMarker.Length) <= yourString.Length)
                  {
                  string testString = yourString.Substring(num, yourMarker.Length);

                  if (testString == yourMarker)
                  {
                  currentInst++;
                  if (currentInst == yourInst)
                  {
                  myReturnValue = num;
                  break;
                  }
                  }
                  num++;
                  }
                  return myReturnValue;
                  }

                  public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
                  {
                  //returns the placement of a string in another string
                  int num = 0;
                  int currentInst = 0;
                  var charArray = yourString.ToArray<char>();
                  int myReturnValue = -1;
                  if (!caseSensitive)
                  {
                  yourString = yourString.ToLower();
                  yourMarker = Char.ToLower(yourMarker);
                  }
                  while (num <= charArray.Length)
                  {
                  if (charArray[num] == yourMarker)
                  {
                  currentInst++;
                  if (currentInst == yourInst)
                  {
                  myReturnValue = num;
                  break;
                  }
                  }
                  num++;
                  }
                  return myReturnValue;
                  }





                  share|improve this answer

































                    1














                    Another RegEx-based solution (untested):



                    int NthIndexOf(string s, char t, int n) {
                    if(n < 0) { throw new ArgumentException(); }
                    if(n==1) { return s.IndexOf(t); }
                    if(t=="") { return 0; }
                    string et = RegEx.Escape(t);
                    string pat = "(?<="
                    + Microsoft.VisualBasic.StrDup(n-1, et + @"[.n]*") + ")"
                    + et;
                    Match m = RegEx.Match(s, pat);
                    return m.Success ? m.Index : -1;
                    }


                    This should be slightly more optimal than requiring RegEx to create a Matches collection, only to discard all but one match.






                    share|improve this answer
























                    • In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                      – Ahmad Mageed
                      Apr 3 '10 at 18:17



















                    1














                        public static int FindOccuranceOf(this string str,char @char, int occurance)
                    {
                    var result = str.Select((x, y) => new { Letter = x, Index = y })
                    .Where(letter => letter.Letter == @char).ToList();
                    if (occurence > result.Count || occurance <= 0)
                    {
                    throw new IndexOutOfRangeException("occurance");
                    }
                    return result[occurance-1].Index ;
                    }





                    share|improve this answer

































                      1














                      Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.



                      public static int NthIndexOf(string text, char searchChar, int nthindex)
                      {
                      int index = -1;
                      try
                      {
                      var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
                      if (takeCount < text.Length) index = takeCount;
                      }
                      catch { }
                      return index;
                      }
                      public static int NthIndexOf(string text, string searchText, int nthindex)
                      {
                      int index = -1;
                      try
                      {
                      Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
                      if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
                      }
                      catch { }
                      return index;
                      }





                      share|improve this answer

































                        1














                        Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):



                        public static int NthIndexOf(this string input, char value, int n)
                        {
                        if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                        int i = -1;
                        do
                        {
                        i = input.IndexOf(value, i + 1);
                        n--;
                        }
                        while (i != -1 && n > 0);

                        return i;
                        }


                        Or to search from the end of the string using LastIndexOf:



                        public static int NthLastIndexOf(this string input, char value, int n)
                        {
                        if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                        int i = input.Length;
                        do
                        {
                        i = input.LastIndexOf(value, i - 1);
                        n--;
                        }
                        while (i != -1 && n > 0);

                        return i;
                        }


                        Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.






                        share|improve this answer































                          1














                          Marc Cals' LINQ Extended for generic.



                             using System;
                          using System.Collections.Generic;
                          using System.Linq;

                          namespace fNns
                          {
                          public class indexer<T> where T : IEquatable<T>
                          {
                          public T t { get; set; }
                          public int index { get; set; }
                          }
                          public static class fN
                          {
                          public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
                          int occurrencePosition) where T : IEquatable<T>
                          {
                          var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                          .Where(item => item.t.Equals(t))
                          .Skip(occurrencePosition - 1)
                          .FirstOrDefault();
                          return result;
                          }
                          public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
                          int occurrencePosition) where T : IEquatable<T>
                          {
                          var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                          .Where(item => item.t.Equals(t))
                          .Skip(occurrencePosition - 1)
                          .FirstOrDefault();
                          return result;
                          }
                          }
                          }


                          Some tests.



                             using System;
                          using System.Collections.Generic;
                          using NUnit.Framework;
                          using Newtonsoft.Json;
                          namespace FindNthNamespace.Tests
                          {

                          public class fNTests
                          {
                          [TestCase("pass", "dtststx", 't', 3, Result = "{"t":"t","index":5}")]
                          [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                          0, 2, Result="{"t":0,"index":10}")]
                          public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                          {
                          Console.WriteLine(scenario);
                          return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
                          }

                          [TestCase("pass", "dtststxx", 't', 3, Result = "{"t":"t","index":6}")]
                          [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                          0, 2, Result = "{"t":0,"index":19}")]
                          public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                          {
                          Console.WriteLine(scenario);
                          return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
                          }


                          }


                          }






                          share|improve this answer

































                            1














                            Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.



                            Here's the string match version:



                            public static int IndexOfNth(this string source, string matchString, 
                            int charInstance,
                            StringComparison stringComparison = StringComparison.CurrentCulture)
                            {
                            if (string.IsNullOrEmpty(source))
                            return -1;

                            int lastPos = 0;
                            int count = 0;

                            while (count < charInstance )
                            {
                            var len = source.Length - lastPos;
                            lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
                            if (lastPos == -1)
                            break;

                            count++;
                            if (count == charInstance)
                            return lastPos;

                            lastPos += matchString.Length;
                            }
                            return -1;
                            }


                            and the char match version:



                            public static int IndexOfNth(string source, char matchChar, int charInstance)        
                            {
                            if (string.IsNullOrEmpty(source))
                            return -1;

                            if (charInstance < 1)
                            return -1;

                            int count = 0;
                            for (int i = 0; i < source.Length; i++)
                            {
                            if (source[i] == matchChar)
                            {
                            count++;
                            if (count == charInstance)
                            return i;
                            }
                            }
                            return -1;
                            }


                            I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.






                            share|improve this answer































                              0














                              string theString = "The String";
                              int index = theString.NthIndexOf("THEVALUE", 3, true);





                              share|improve this answer































                                0














                                public static int IndexOfAny(this string str, string values, int startIndex, out string selectedItem)
                                {
                                int first = -1;
                                selectedItem = null;
                                foreach (string item in values)
                                {
                                int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
                                if (i >= 0)
                                {
                                if (first > 0)
                                {
                                if (i < first)
                                {
                                first = i;
                                selectedItem = item;
                                }
                                }
                                else
                                {
                                first = i;
                                selectedItem = item;
                                }
                                }
                                }
                                return first;
                                }





                                share|improve this answer























                                  Your Answer






                                  StackExchange.ifUsing("editor", function () {
                                  StackExchange.using("externalEditor", function () {
                                  StackExchange.using("snippets", function () {
                                  StackExchange.snippets.init();
                                  });
                                  });
                                  }, "code-snippets");

                                  StackExchange.ready(function() {
                                  var channelOptions = {
                                  tags: "".split(" "),
                                  id: "1"
                                  };
                                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                  StackExchange.using("externalEditor", function() {
                                  // Have to fire editor after snippets, if snippets enabled
                                  if (StackExchange.settings.snippets.snippetsEnabled) {
                                  StackExchange.using("snippets", function() {
                                  createEditor();
                                  });
                                  }
                                  else {
                                  createEditor();
                                  }
                                  });

                                  function createEditor() {
                                  StackExchange.prepareEditor({
                                  heartbeatType: 'answer',
                                  autoActivateHeartbeat: false,
                                  convertImagesToLinks: true,
                                  noModals: true,
                                  showLowRepImageUploadWarning: true,
                                  reputationToPostImages: 10,
                                  bindNavPrevention: true,
                                  postfix: "",
                                  imageUploader: {
                                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                  allowUrls: true
                                  },
                                  onDemand: true,
                                  discardSelector: ".discard-answer"
                                  ,immediatelyShowMarkdownHelp:true
                                  });


                                  }
                                  });














                                  draft saved

                                  draft discarded


















                                  StackExchange.ready(
                                  function () {
                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2571716%2ffind-nth-occurrence-of-a-character-in-a-string%23new-answer', 'question_page');
                                  }
                                  );

                                  Post as a guest















                                  Required, but never shown

























                                  21 Answers
                                  21






                                  active

                                  oldest

                                  votes








                                  21 Answers
                                  21






                                  active

                                  oldest

                                  votes









                                  active

                                  oldest

                                  votes






                                  active

                                  oldest

                                  votes









                                  71














                                  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.






                                  share|improve this answer





















                                  • 5





                                    Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                    – Mike
                                    Feb 22 '14 at 15:57






                                  • 1





                                    love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                    – user734028
                                    Jan 8 '18 at 6:18
















                                  71














                                  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.






                                  share|improve this answer





















                                  • 5





                                    Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                    – Mike
                                    Feb 22 '14 at 15:57






                                  • 1





                                    love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                    – user734028
                                    Jan 8 '18 at 6:18














                                  71












                                  71








                                  71







                                  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.






                                  share|improve this answer















                                  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.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Apr 5 '14 at 10:30









                                  AGuyCalledGerald

                                  4,5101454100




                                  4,5101454100










                                  answered Apr 3 '10 at 15:54









                                  Mike TwoMike Two

                                  34.3k77093




                                  34.3k77093








                                  • 5





                                    Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                    – Mike
                                    Feb 22 '14 at 15:57






                                  • 1





                                    love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                    – user734028
                                    Jan 8 '18 at 6:18














                                  • 5





                                    Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                    – Mike
                                    Feb 22 '14 at 15:57






                                  • 1





                                    love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                    – user734028
                                    Jan 8 '18 at 6:18








                                  5




                                  5





                                  Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                  – Mike
                                  Feb 22 '14 at 15:57





                                  Great approach. Nice and clean, easy to read, easy to maintain, and excellent performance.

                                  – Mike
                                  Feb 22 '14 at 15:57




                                  1




                                  1





                                  love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                  – user734028
                                  Jan 8 '18 at 6:18





                                  love for loops like these, not only they give excellent performance, but you cant go wrong with them since everything is crystal clear and right in front of your eyes. You write a linq and some developer puts it in a loop not understanding the cost and everyone keeps wondering where is the performance bottleneck.

                                  – user734028
                                  Jan 8 '18 at 6:18













                                  18














                                  There is a minor bug in previous solution.



                                  Here is some updated code:



                                  s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();





                                  share|improve this answer





















                                  • 1





                                    What does it return if the character is not found?

                                    – Timuçin
                                    Sep 29 '14 at 10:53











                                  • It returns the length/count of the string s. You need to check for that value.

                                    – Yoky
                                    Nov 12 '15 at 0:34
















                                  18














                                  There is a minor bug in previous solution.



                                  Here is some updated code:



                                  s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();





                                  share|improve this answer





















                                  • 1





                                    What does it return if the character is not found?

                                    – Timuçin
                                    Sep 29 '14 at 10:53











                                  • It returns the length/count of the string s. You need to check for that value.

                                    – Yoky
                                    Nov 12 '15 at 0:34














                                  18












                                  18








                                  18







                                  There is a minor bug in previous solution.



                                  Here is some updated code:



                                  s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();





                                  share|improve this answer















                                  There is a minor bug in previous solution.



                                  Here is some updated code:



                                  s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 26 '15 at 17:07









                                  dx_over_dt

                                  1,60342347




                                  1,60342347










                                  answered Mar 28 '12 at 13:20









                                  shalin shahshalin shah

                                  18112




                                  18112








                                  • 1





                                    What does it return if the character is not found?

                                    – Timuçin
                                    Sep 29 '14 at 10:53











                                  • It returns the length/count of the string s. You need to check for that value.

                                    – Yoky
                                    Nov 12 '15 at 0:34














                                  • 1





                                    What does it return if the character is not found?

                                    – Timuçin
                                    Sep 29 '14 at 10:53











                                  • It returns the length/count of the string s. You need to check for that value.

                                    – Yoky
                                    Nov 12 '15 at 0:34








                                  1




                                  1





                                  What does it return if the character is not found?

                                  – Timuçin
                                  Sep 29 '14 at 10:53





                                  What does it return if the character is not found?

                                  – Timuçin
                                  Sep 29 '14 at 10:53













                                  It returns the length/count of the string s. You need to check for that value.

                                  – Yoky
                                  Nov 12 '15 at 0:34





                                  It returns the length/count of the string s. You need to check for that value.

                                  – Yoky
                                  Nov 12 '15 at 0:34











                                  12














                                  Update: Index of Nth occurance one-liner:



                                  int NthOccurence(string s, char t, int n)
                                  {
                                  s.TakeWhile(c => n - (c == t)?1:0 > 0).Count();
                                  }




                                  Use these at your own risk. This looks like homework, so I left a few bugs in there for your to find:



                                  int CountChars(string s, char t)
                                  {
                                  int count = 0;
                                  foreach (char c in s)
                                  if (s.Equals(t)) count ++;
                                  return count;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  return s.Length - s.Replace(t.ToString(), "").Length;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  Regex r = new Regex("[\" + t + "]");
                                  return r.Match(s).Count;
                                  }





                                  share|improve this answer





















                                  • 2





                                    Your one-liner example doesn't work because the value of n is never changed.

                                    – Dave Neeley
                                    Jun 3 '11 at 18:17






                                  • 2





                                    Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                    – nullable
                                    Oct 26 '11 at 20:15








                                  • 1





                                    −1, "so I left a few bugs in there for your to find"

                                    – Zanon
                                    Jan 9 '18 at 13:40
















                                  12














                                  Update: Index of Nth occurance one-liner:



                                  int NthOccurence(string s, char t, int n)
                                  {
                                  s.TakeWhile(c => n - (c == t)?1:0 > 0).Count();
                                  }




                                  Use these at your own risk. This looks like homework, so I left a few bugs in there for your to find:



                                  int CountChars(string s, char t)
                                  {
                                  int count = 0;
                                  foreach (char c in s)
                                  if (s.Equals(t)) count ++;
                                  return count;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  return s.Length - s.Replace(t.ToString(), "").Length;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  Regex r = new Regex("[\" + t + "]");
                                  return r.Match(s).Count;
                                  }





                                  share|improve this answer





















                                  • 2





                                    Your one-liner example doesn't work because the value of n is never changed.

                                    – Dave Neeley
                                    Jun 3 '11 at 18:17






                                  • 2





                                    Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                    – nullable
                                    Oct 26 '11 at 20:15








                                  • 1





                                    −1, "so I left a few bugs in there for your to find"

                                    – Zanon
                                    Jan 9 '18 at 13:40














                                  12












                                  12








                                  12







                                  Update: Index of Nth occurance one-liner:



                                  int NthOccurence(string s, char t, int n)
                                  {
                                  s.TakeWhile(c => n - (c == t)?1:0 > 0).Count();
                                  }




                                  Use these at your own risk. This looks like homework, so I left a few bugs in there for your to find:



                                  int CountChars(string s, char t)
                                  {
                                  int count = 0;
                                  foreach (char c in s)
                                  if (s.Equals(t)) count ++;
                                  return count;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  return s.Length - s.Replace(t.ToString(), "").Length;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  Regex r = new Regex("[\" + t + "]");
                                  return r.Match(s).Count;
                                  }





                                  share|improve this answer















                                  Update: Index of Nth occurance one-liner:



                                  int NthOccurence(string s, char t, int n)
                                  {
                                  s.TakeWhile(c => n - (c == t)?1:0 > 0).Count();
                                  }




                                  Use these at your own risk. This looks like homework, so I left a few bugs in there for your to find:



                                  int CountChars(string s, char t)
                                  {
                                  int count = 0;
                                  foreach (char c in s)
                                  if (s.Equals(t)) count ++;
                                  return count;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  return s.Length - s.Replace(t.ToString(), "").Length;
                                  }


                                  .



                                  int CountChars(string s, char t)
                                  {
                                  Regex r = new Regex("[\" + t + "]");
                                  return r.Match(s).Count;
                                  }






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Apr 3 '10 at 16:12

























                                  answered Apr 3 '10 at 15:50









                                  Joel CoehoornJoel Coehoorn

                                  307k95490721




                                  307k95490721








                                  • 2





                                    Your one-liner example doesn't work because the value of n is never changed.

                                    – Dave Neeley
                                    Jun 3 '11 at 18:17






                                  • 2





                                    Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                    – nullable
                                    Oct 26 '11 at 20:15








                                  • 1





                                    −1, "so I left a few bugs in there for your to find"

                                    – Zanon
                                    Jan 9 '18 at 13:40














                                  • 2





                                    Your one-liner example doesn't work because the value of n is never changed.

                                    – Dave Neeley
                                    Jun 3 '11 at 18:17






                                  • 2





                                    Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                    – nullable
                                    Oct 26 '11 at 20:15








                                  • 1





                                    −1, "so I left a few bugs in there for your to find"

                                    – Zanon
                                    Jan 9 '18 at 13:40








                                  2




                                  2





                                  Your one-liner example doesn't work because the value of n is never changed.

                                  – Dave Neeley
                                  Jun 3 '11 at 18:17





                                  Your one-liner example doesn't work because the value of n is never changed.

                                  – Dave Neeley
                                  Jun 3 '11 at 18:17




                                  2




                                  2





                                  Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                  – nullable
                                  Oct 26 '11 at 20:15







                                  Nice solution, though this isn't a true "one-liner" as a variable needs to be defined out of scope of the lambda. s.TakeWhile(c => ((n -= (c == 't')) ? 1 : 0) > 0).Count();

                                  – nullable
                                  Oct 26 '11 at 20:15






                                  1




                                  1





                                  −1, "so I left a few bugs in there for your to find"

                                  – Zanon
                                  Jan 9 '18 at 13:40





                                  −1, "so I left a few bugs in there for your to find"

                                  – Zanon
                                  Jan 9 '18 at 13:40











                                  8














                                  Here's another LINQ solution:



                                  string input = "dtststx";
                                  char searchChar = 't';
                                  int occurrencePosition = 3; // third occurrence of the char
                                  var result = input.Select((c, i) => new { Char = c, Index = i })
                                  .Where(item => item.Char == searchChar)
                                  .Skip(occurrencePosition - 1)
                                  .FirstOrDefault();

                                  if (result != null)
                                  {
                                  Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
                                  occurrencePosition, searchChar, result.Index);
                                  }
                                  else
                                  {
                                  Console.WriteLine("Position {0} of '{1}' not found!",
                                  occurrencePosition, searchChar);
                                  }




                                  Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.



                                  string input = "dtststx";
                                  char searchChar = 't';
                                  int occurrencePosition = 3; // third occurrence of the char

                                  Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
                                  .Cast<Match>()
                                  .Skip(occurrencePosition - 1)
                                  .FirstOrDefault();

                                  if (match != null)
                                  Console.WriteLine("Index: " + match.Index);
                                  else
                                  Console.WriteLine("Match not found!");





                                  share|improve this answer






























                                    8














                                    Here's another LINQ solution:



                                    string input = "dtststx";
                                    char searchChar = 't';
                                    int occurrencePosition = 3; // third occurrence of the char
                                    var result = input.Select((c, i) => new { Char = c, Index = i })
                                    .Where(item => item.Char == searchChar)
                                    .Skip(occurrencePosition - 1)
                                    .FirstOrDefault();

                                    if (result != null)
                                    {
                                    Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
                                    occurrencePosition, searchChar, result.Index);
                                    }
                                    else
                                    {
                                    Console.WriteLine("Position {0} of '{1}' not found!",
                                    occurrencePosition, searchChar);
                                    }




                                    Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.



                                    string input = "dtststx";
                                    char searchChar = 't';
                                    int occurrencePosition = 3; // third occurrence of the char

                                    Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
                                    .Cast<Match>()
                                    .Skip(occurrencePosition - 1)
                                    .FirstOrDefault();

                                    if (match != null)
                                    Console.WriteLine("Index: " + match.Index);
                                    else
                                    Console.WriteLine("Match not found!");





                                    share|improve this answer




























                                      8












                                      8








                                      8







                                      Here's another LINQ solution:



                                      string input = "dtststx";
                                      char searchChar = 't';
                                      int occurrencePosition = 3; // third occurrence of the char
                                      var result = input.Select((c, i) => new { Char = c, Index = i })
                                      .Where(item => item.Char == searchChar)
                                      .Skip(occurrencePosition - 1)
                                      .FirstOrDefault();

                                      if (result != null)
                                      {
                                      Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
                                      occurrencePosition, searchChar, result.Index);
                                      }
                                      else
                                      {
                                      Console.WriteLine("Position {0} of '{1}' not found!",
                                      occurrencePosition, searchChar);
                                      }




                                      Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.



                                      string input = "dtststx";
                                      char searchChar = 't';
                                      int occurrencePosition = 3; // third occurrence of the char

                                      Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
                                      .Cast<Match>()
                                      .Skip(occurrencePosition - 1)
                                      .FirstOrDefault();

                                      if (match != null)
                                      Console.WriteLine("Index: " + match.Index);
                                      else
                                      Console.WriteLine("Match not found!");





                                      share|improve this answer















                                      Here's another LINQ solution:



                                      string input = "dtststx";
                                      char searchChar = 't';
                                      int occurrencePosition = 3; // third occurrence of the char
                                      var result = input.Select((c, i) => new { Char = c, Index = i })
                                      .Where(item => item.Char == searchChar)
                                      .Skip(occurrencePosition - 1)
                                      .FirstOrDefault();

                                      if (result != null)
                                      {
                                      Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
                                      occurrencePosition, searchChar, result.Index);
                                      }
                                      else
                                      {
                                      Console.WriteLine("Position {0} of '{1}' not found!",
                                      occurrencePosition, searchChar);
                                      }




                                      Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.



                                      string input = "dtststx";
                                      char searchChar = 't';
                                      int occurrencePosition = 3; // third occurrence of the char

                                      Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
                                      .Cast<Match>()
                                      .Skip(occurrencePosition - 1)
                                      .FirstOrDefault();

                                      if (match != null)
                                      Console.WriteLine("Index: " + match.Index);
                                      else
                                      Console.WriteLine("Match not found!");






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Apr 3 '10 at 16:54

























                                      answered Apr 3 '10 at 16:47









                                      Ahmad MageedAhmad Mageed

                                      76.6k14135161




                                      76.6k14135161























                                          8














                                          Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):



                                          public static int IndexOfNth(
                                          this string input, string value, int startIndex, int nth)
                                          {
                                          if (nth < 1)
                                          throw new NotSupportedException("Param 'nth' must be greater than 0!");
                                          if (nth == 1)
                                          return input.IndexOf(value, startIndex);

                                          return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
                                          }


                                          Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):



                                          [Test]
                                          public void TestIndexOfNthWorksForNth1()
                                          {
                                          const string input = "foo<br />bar<br />baz<br />";
                                          Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
                                          }

                                          [Test]
                                          public void TestIndexOfNthWorksForNth2()
                                          {
                                          const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                          Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
                                          }

                                          [Test]
                                          public void TestIndexOfNthWorksForNth3()
                                          {
                                          const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                          Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
                                          }





                                          share|improve this answer






























                                            8














                                            Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):



                                            public static int IndexOfNth(
                                            this string input, string value, int startIndex, int nth)
                                            {
                                            if (nth < 1)
                                            throw new NotSupportedException("Param 'nth' must be greater than 0!");
                                            if (nth == 1)
                                            return input.IndexOf(value, startIndex);

                                            return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
                                            }


                                            Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):



                                            [Test]
                                            public void TestIndexOfNthWorksForNth1()
                                            {
                                            const string input = "foo<br />bar<br />baz<br />";
                                            Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
                                            }

                                            [Test]
                                            public void TestIndexOfNthWorksForNth2()
                                            {
                                            const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                            Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
                                            }

                                            [Test]
                                            public void TestIndexOfNthWorksForNth3()
                                            {
                                            const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                            Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
                                            }





                                            share|improve this answer




























                                              8












                                              8








                                              8







                                              Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):



                                              public static int IndexOfNth(
                                              this string input, string value, int startIndex, int nth)
                                              {
                                              if (nth < 1)
                                              throw new NotSupportedException("Param 'nth' must be greater than 0!");
                                              if (nth == 1)
                                              return input.IndexOf(value, startIndex);

                                              return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
                                              }


                                              Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):



                                              [Test]
                                              public void TestIndexOfNthWorksForNth1()
                                              {
                                              const string input = "foo<br />bar<br />baz<br />";
                                              Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
                                              }

                                              [Test]
                                              public void TestIndexOfNthWorksForNth2()
                                              {
                                              const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                              Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
                                              }

                                              [Test]
                                              public void TestIndexOfNthWorksForNth3()
                                              {
                                              const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                              Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
                                              }





                                              share|improve this answer















                                              Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):



                                              public static int IndexOfNth(
                                              this string input, string value, int startIndex, int nth)
                                              {
                                              if (nth < 1)
                                              throw new NotSupportedException("Param 'nth' must be greater than 0!");
                                              if (nth == 1)
                                              return input.IndexOf(value, startIndex);

                                              return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
                                              }


                                              Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):



                                              [Test]
                                              public void TestIndexOfNthWorksForNth1()
                                              {
                                              const string input = "foo<br />bar<br />baz<br />";
                                              Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
                                              }

                                              [Test]
                                              public void TestIndexOfNthWorksForNth2()
                                              {
                                              const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                              Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
                                              }

                                              [Test]
                                              public void TestIndexOfNthWorksForNth3()
                                              {
                                              const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
                                              Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
                                              }






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jun 17 '15 at 20:45









                                              Marc Cals

                                              2,03622137




                                              2,03622137










                                              answered Mar 22 '11 at 3:37









                                              Tod ThomsonTod Thomson

                                              3,65812832




                                              3,65812832























                                                  4














                                                  Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:



                                                  yourString.Where(c => c == 't').Count();





                                                  share|improve this answer



















                                                  • 2





                                                    @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                    – Mike Two
                                                    Apr 3 '10 at 16:04






                                                  • 9





                                                    Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                    – dx_over_dt
                                                    Jun 26 '15 at 16:21
















                                                  4














                                                  Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:



                                                  yourString.Where(c => c == 't').Count();





                                                  share|improve this answer



















                                                  • 2





                                                    @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                    – Mike Two
                                                    Apr 3 '10 at 16:04






                                                  • 9





                                                    Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                    – dx_over_dt
                                                    Jun 26 '15 at 16:21














                                                  4












                                                  4








                                                  4







                                                  Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:



                                                  yourString.Where(c => c == 't').Count();





                                                  share|improve this answer













                                                  Joel's answer is good (and I upvoted it). Here is a LINQ-based solution:



                                                  yourString.Where(c => c == 't').Count();






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Apr 3 '10 at 15:52









                                                  Andrew HareAndrew Hare

                                                  275k53576599




                                                  275k53576599








                                                  • 2





                                                    @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                    – Mike Two
                                                    Apr 3 '10 at 16:04






                                                  • 9





                                                    Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                    – dx_over_dt
                                                    Jun 26 '15 at 16:21














                                                  • 2





                                                    @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                    – Mike Two
                                                    Apr 3 '10 at 16:04






                                                  • 9





                                                    Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                    – dx_over_dt
                                                    Jun 26 '15 at 16:21








                                                  2




                                                  2





                                                  @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                  – Mike Two
                                                  Apr 3 '10 at 16:04





                                                  @Andrew - you can shorten this by skipping the Where and passing the predicate to the Count method. Not that there is anything wrong with the way it is.

                                                  – Mike Two
                                                  Apr 3 '10 at 16:04




                                                  9




                                                  9





                                                  Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                  – dx_over_dt
                                                  Jun 26 '15 at 16:21





                                                  Won't this just find how many occurrences of a character there are rather than the index of the nth one?

                                                  – dx_over_dt
                                                  Jun 26 '15 at 16:21











                                                  4














                                                  ranomore correctly commented that Joel Coehoorn's one-liner doesn't work.



                                                  Here is a two-liner that does work, a string extension method that returns the 0-based index of the nth occurrence of a character, or -1 if no nth occurrence exists:



                                                  public static class StringExtensions
                                                  {
                                                  public static int NthIndexOf(this string s, char c, int n)
                                                  {
                                                  var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count();
                                                  return takeCount == s.Length ? -1 : takeCount;
                                                  }
                                                  }





                                                  share|improve this answer




























                                                    4














                                                    ranomore correctly commented that Joel Coehoorn's one-liner doesn't work.



                                                    Here is a two-liner that does work, a string extension method that returns the 0-based index of the nth occurrence of a character, or -1 if no nth occurrence exists:



                                                    public static class StringExtensions
                                                    {
                                                    public static int NthIndexOf(this string s, char c, int n)
                                                    {
                                                    var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count();
                                                    return takeCount == s.Length ? -1 : takeCount;
                                                    }
                                                    }





                                                    share|improve this answer


























                                                      4












                                                      4








                                                      4







                                                      ranomore correctly commented that Joel Coehoorn's one-liner doesn't work.



                                                      Here is a two-liner that does work, a string extension method that returns the 0-based index of the nth occurrence of a character, or -1 if no nth occurrence exists:



                                                      public static class StringExtensions
                                                      {
                                                      public static int NthIndexOf(this string s, char c, int n)
                                                      {
                                                      var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count();
                                                      return takeCount == s.Length ? -1 : takeCount;
                                                      }
                                                      }





                                                      share|improve this answer













                                                      ranomore correctly commented that Joel Coehoorn's one-liner doesn't work.



                                                      Here is a two-liner that does work, a string extension method that returns the 0-based index of the nth occurrence of a character, or -1 if no nth occurrence exists:



                                                      public static class StringExtensions
                                                      {
                                                      public static int NthIndexOf(this string s, char c, int n)
                                                      {
                                                      var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count();
                                                      return takeCount == s.Length ? -1 : takeCount;
                                                      }
                                                      }






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Jun 23 '11 at 7:30









                                                      Wayne MaurerWayne Maurer

                                                      8,66332336




                                                      8,66332336























                                                          3














                                                          Here is a fun way to do it



                                                               int i = 0;
                                                          string s="asdasdasd";
                                                          int n = 3;
                                                          s.Where(b => (b == 'd') && (i++ == n));
                                                          return i;





                                                          share|improve this answer




























                                                            3














                                                            Here is a fun way to do it



                                                                 int i = 0;
                                                            string s="asdasdasd";
                                                            int n = 3;
                                                            s.Where(b => (b == 'd') && (i++ == n));
                                                            return i;





                                                            share|improve this answer


























                                                              3












                                                              3








                                                              3







                                                              Here is a fun way to do it



                                                                   int i = 0;
                                                              string s="asdasdasd";
                                                              int n = 3;
                                                              s.Where(b => (b == 'd') && (i++ == n));
                                                              return i;





                                                              share|improve this answer













                                                              Here is a fun way to do it



                                                                   int i = 0;
                                                              string s="asdasdasd";
                                                              int n = 3;
                                                              s.Where(b => (b == 'd') && (i++ == n));
                                                              return i;






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Apr 3 '10 at 16:54









                                                              DestedDested

                                                              2,742104569




                                                              2,742104569























                                                                  3














                                                                  string result = "i am 'bansal.vks@gmail.com'"; // string

                                                                  int in1 = result.IndexOf('''); // get the index of first quote

                                                                  int in2 = result.IndexOf(''', in1 + 1); // get the index of second

                                                                  string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes





                                                                  share|improve this answer






























                                                                    3














                                                                    string result = "i am 'bansal.vks@gmail.com'"; // string

                                                                    int in1 = result.IndexOf('''); // get the index of first quote

                                                                    int in2 = result.IndexOf(''', in1 + 1); // get the index of second

                                                                    string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes





                                                                    share|improve this answer




























                                                                      3












                                                                      3








                                                                      3







                                                                      string result = "i am 'bansal.vks@gmail.com'"; // string

                                                                      int in1 = result.IndexOf('''); // get the index of first quote

                                                                      int in2 = result.IndexOf(''', in1 + 1); // get the index of second

                                                                      string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes





                                                                      share|improve this answer















                                                                      string result = "i am 'bansal.vks@gmail.com'"; // string

                                                                      int in1 = result.IndexOf('''); // get the index of first quote

                                                                      int in2 = result.IndexOf(''', in1 + 1); // get the index of second

                                                                      string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes






                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited May 22 '15 at 17:27









                                                                      Eugene

                                                                      1,61931320




                                                                      1,61931320










                                                                      answered May 22 '15 at 16:49









                                                                      Vikas BansalVikas Bansal

                                                                      3,83043361




                                                                      3,83043361























                                                                          3














                                                                          I add another answer that run pretty fast compared to others methods



                                                                          private static int IndexOfNth(string str, char c, int nth, int startPosition = 0)
                                                                          {
                                                                          int index = str.IndexOf(c, startPosition);
                                                                          if (index >= 0 && nth > 1)
                                                                          {
                                                                          return IndexOfNth(str, c, nth - 1, index + 1);
                                                                          }

                                                                          return index;
                                                                          }





                                                                          share|improve this answer




























                                                                            3














                                                                            I add another answer that run pretty fast compared to others methods



                                                                            private static int IndexOfNth(string str, char c, int nth, int startPosition = 0)
                                                                            {
                                                                            int index = str.IndexOf(c, startPosition);
                                                                            if (index >= 0 && nth > 1)
                                                                            {
                                                                            return IndexOfNth(str, c, nth - 1, index + 1);
                                                                            }

                                                                            return index;
                                                                            }





                                                                            share|improve this answer


























                                                                              3












                                                                              3








                                                                              3







                                                                              I add another answer that run pretty fast compared to others methods



                                                                              private static int IndexOfNth(string str, char c, int nth, int startPosition = 0)
                                                                              {
                                                                              int index = str.IndexOf(c, startPosition);
                                                                              if (index >= 0 && nth > 1)
                                                                              {
                                                                              return IndexOfNth(str, c, nth - 1, index + 1);
                                                                              }

                                                                              return index;
                                                                              }





                                                                              share|improve this answer













                                                                              I add another answer that run pretty fast compared to others methods



                                                                              private static int IndexOfNth(string str, char c, int nth, int startPosition = 0)
                                                                              {
                                                                              int index = str.IndexOf(c, startPosition);
                                                                              if (index >= 0 && nth > 1)
                                                                              {
                                                                              return IndexOfNth(str, c, nth - 1, index + 1);
                                                                              }

                                                                              return index;
                                                                              }






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Jun 17 '15 at 19:40









                                                                              Marc CalsMarc Cals

                                                                              2,03622137




                                                                              2,03622137























                                                                                  2














                                                                                  you can do this work with Regular Expressions.



                                                                                          string input = "dtststx";
                                                                                  char searching_char = 't';
                                                                                  int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index;


                                                                                  best regard.






                                                                                  share|improve this answer




























                                                                                    2














                                                                                    you can do this work with Regular Expressions.



                                                                                            string input = "dtststx";
                                                                                    char searching_char = 't';
                                                                                    int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index;


                                                                                    best regard.






                                                                                    share|improve this answer


























                                                                                      2












                                                                                      2








                                                                                      2







                                                                                      you can do this work with Regular Expressions.



                                                                                              string input = "dtststx";
                                                                                      char searching_char = 't';
                                                                                      int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index;


                                                                                      best regard.






                                                                                      share|improve this answer













                                                                                      you can do this work with Regular Expressions.



                                                                                              string input = "dtststx";
                                                                                      char searching_char = 't';
                                                                                      int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index;


                                                                                      best regard.







                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Dec 19 '11 at 15:29









                                                                                      EMAIEMAI

                                                                                      1178




                                                                                      1178























                                                                                          2














                                                                                          public int GetNthOccurrenceOfChar(string s, char c, int occ)
                                                                                          {
                                                                                          return String.Join(c.ToString(), s.Split(new char { c }, StringSplitOptions.None).Take(occ)).Length;
                                                                                          }





                                                                                          share|improve this answer




























                                                                                            2














                                                                                            public int GetNthOccurrenceOfChar(string s, char c, int occ)
                                                                                            {
                                                                                            return String.Join(c.ToString(), s.Split(new char { c }, StringSplitOptions.None).Take(occ)).Length;
                                                                                            }





                                                                                            share|improve this answer


























                                                                                              2












                                                                                              2








                                                                                              2







                                                                                              public int GetNthOccurrenceOfChar(string s, char c, int occ)
                                                                                              {
                                                                                              return String.Join(c.ToString(), s.Split(new char { c }, StringSplitOptions.None).Take(occ)).Length;
                                                                                              }





                                                                                              share|improve this answer













                                                                                              public int GetNthOccurrenceOfChar(string s, char c, int occ)
                                                                                              {
                                                                                              return String.Join(c.ToString(), s.Split(new char { c }, StringSplitOptions.None).Take(occ)).Length;
                                                                                              }






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Apr 2 '14 at 14:19









                                                                                              AGuyCalledGeraldAGuyCalledGerald

                                                                                              4,5101454100




                                                                                              4,5101454100























                                                                                                  2














                                                                                                  if your interested you can also create string extension methods like so:



                                                                                                       public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                  {
                                                                                                  //returns the placement of a string in another string
                                                                                                  int num = 0;
                                                                                                  int currentInst = 0;
                                                                                                  //if optional argument, case sensitive is false convert string and marker to lowercase
                                                                                                  if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
                                                                                                  int myReturnValue = -1; //if nothing is found the returned integer is negative 1
                                                                                                  while ((num + yourMarker.Length) <= yourString.Length)
                                                                                                  {
                                                                                                  string testString = yourString.Substring(num, yourMarker.Length);

                                                                                                  if (testString == yourMarker)
                                                                                                  {
                                                                                                  currentInst++;
                                                                                                  if (currentInst == yourInst)
                                                                                                  {
                                                                                                  myReturnValue = num;
                                                                                                  break;
                                                                                                  }
                                                                                                  }
                                                                                                  num++;
                                                                                                  }
                                                                                                  return myReturnValue;
                                                                                                  }

                                                                                                  public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                  {
                                                                                                  //returns the placement of a string in another string
                                                                                                  int num = 0;
                                                                                                  int currentInst = 0;
                                                                                                  var charArray = yourString.ToArray<char>();
                                                                                                  int myReturnValue = -1;
                                                                                                  if (!caseSensitive)
                                                                                                  {
                                                                                                  yourString = yourString.ToLower();
                                                                                                  yourMarker = Char.ToLower(yourMarker);
                                                                                                  }
                                                                                                  while (num <= charArray.Length)
                                                                                                  {
                                                                                                  if (charArray[num] == yourMarker)
                                                                                                  {
                                                                                                  currentInst++;
                                                                                                  if (currentInst == yourInst)
                                                                                                  {
                                                                                                  myReturnValue = num;
                                                                                                  break;
                                                                                                  }
                                                                                                  }
                                                                                                  num++;
                                                                                                  }
                                                                                                  return myReturnValue;
                                                                                                  }





                                                                                                  share|improve this answer






























                                                                                                    2














                                                                                                    if your interested you can also create string extension methods like so:



                                                                                                         public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                    {
                                                                                                    //returns the placement of a string in another string
                                                                                                    int num = 0;
                                                                                                    int currentInst = 0;
                                                                                                    //if optional argument, case sensitive is false convert string and marker to lowercase
                                                                                                    if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
                                                                                                    int myReturnValue = -1; //if nothing is found the returned integer is negative 1
                                                                                                    while ((num + yourMarker.Length) <= yourString.Length)
                                                                                                    {
                                                                                                    string testString = yourString.Substring(num, yourMarker.Length);

                                                                                                    if (testString == yourMarker)
                                                                                                    {
                                                                                                    currentInst++;
                                                                                                    if (currentInst == yourInst)
                                                                                                    {
                                                                                                    myReturnValue = num;
                                                                                                    break;
                                                                                                    }
                                                                                                    }
                                                                                                    num++;
                                                                                                    }
                                                                                                    return myReturnValue;
                                                                                                    }

                                                                                                    public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                    {
                                                                                                    //returns the placement of a string in another string
                                                                                                    int num = 0;
                                                                                                    int currentInst = 0;
                                                                                                    var charArray = yourString.ToArray<char>();
                                                                                                    int myReturnValue = -1;
                                                                                                    if (!caseSensitive)
                                                                                                    {
                                                                                                    yourString = yourString.ToLower();
                                                                                                    yourMarker = Char.ToLower(yourMarker);
                                                                                                    }
                                                                                                    while (num <= charArray.Length)
                                                                                                    {
                                                                                                    if (charArray[num] == yourMarker)
                                                                                                    {
                                                                                                    currentInst++;
                                                                                                    if (currentInst == yourInst)
                                                                                                    {
                                                                                                    myReturnValue = num;
                                                                                                    break;
                                                                                                    }
                                                                                                    }
                                                                                                    num++;
                                                                                                    }
                                                                                                    return myReturnValue;
                                                                                                    }





                                                                                                    share|improve this answer




























                                                                                                      2












                                                                                                      2








                                                                                                      2







                                                                                                      if your interested you can also create string extension methods like so:



                                                                                                           public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                      {
                                                                                                      //returns the placement of a string in another string
                                                                                                      int num = 0;
                                                                                                      int currentInst = 0;
                                                                                                      //if optional argument, case sensitive is false convert string and marker to lowercase
                                                                                                      if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
                                                                                                      int myReturnValue = -1; //if nothing is found the returned integer is negative 1
                                                                                                      while ((num + yourMarker.Length) <= yourString.Length)
                                                                                                      {
                                                                                                      string testString = yourString.Substring(num, yourMarker.Length);

                                                                                                      if (testString == yourMarker)
                                                                                                      {
                                                                                                      currentInst++;
                                                                                                      if (currentInst == yourInst)
                                                                                                      {
                                                                                                      myReturnValue = num;
                                                                                                      break;
                                                                                                      }
                                                                                                      }
                                                                                                      num++;
                                                                                                      }
                                                                                                      return myReturnValue;
                                                                                                      }

                                                                                                      public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                      {
                                                                                                      //returns the placement of a string in another string
                                                                                                      int num = 0;
                                                                                                      int currentInst = 0;
                                                                                                      var charArray = yourString.ToArray<char>();
                                                                                                      int myReturnValue = -1;
                                                                                                      if (!caseSensitive)
                                                                                                      {
                                                                                                      yourString = yourString.ToLower();
                                                                                                      yourMarker = Char.ToLower(yourMarker);
                                                                                                      }
                                                                                                      while (num <= charArray.Length)
                                                                                                      {
                                                                                                      if (charArray[num] == yourMarker)
                                                                                                      {
                                                                                                      currentInst++;
                                                                                                      if (currentInst == yourInst)
                                                                                                      {
                                                                                                      myReturnValue = num;
                                                                                                      break;
                                                                                                      }
                                                                                                      }
                                                                                                      num++;
                                                                                                      }
                                                                                                      return myReturnValue;
                                                                                                      }





                                                                                                      share|improve this answer















                                                                                                      if your interested you can also create string extension methods like so:



                                                                                                           public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                      {
                                                                                                      //returns the placement of a string in another string
                                                                                                      int num = 0;
                                                                                                      int currentInst = 0;
                                                                                                      //if optional argument, case sensitive is false convert string and marker to lowercase
                                                                                                      if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
                                                                                                      int myReturnValue = -1; //if nothing is found the returned integer is negative 1
                                                                                                      while ((num + yourMarker.Length) <= yourString.Length)
                                                                                                      {
                                                                                                      string testString = yourString.Substring(num, yourMarker.Length);

                                                                                                      if (testString == yourMarker)
                                                                                                      {
                                                                                                      currentInst++;
                                                                                                      if (currentInst == yourInst)
                                                                                                      {
                                                                                                      myReturnValue = num;
                                                                                                      break;
                                                                                                      }
                                                                                                      }
                                                                                                      num++;
                                                                                                      }
                                                                                                      return myReturnValue;
                                                                                                      }

                                                                                                      public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
                                                                                                      {
                                                                                                      //returns the placement of a string in another string
                                                                                                      int num = 0;
                                                                                                      int currentInst = 0;
                                                                                                      var charArray = yourString.ToArray<char>();
                                                                                                      int myReturnValue = -1;
                                                                                                      if (!caseSensitive)
                                                                                                      {
                                                                                                      yourString = yourString.ToLower();
                                                                                                      yourMarker = Char.ToLower(yourMarker);
                                                                                                      }
                                                                                                      while (num <= charArray.Length)
                                                                                                      {
                                                                                                      if (charArray[num] == yourMarker)
                                                                                                      {
                                                                                                      currentInst++;
                                                                                                      if (currentInst == yourInst)
                                                                                                      {
                                                                                                      myReturnValue = num;
                                                                                                      break;
                                                                                                      }
                                                                                                      }
                                                                                                      num++;
                                                                                                      }
                                                                                                      return myReturnValue;
                                                                                                      }






                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited Jul 6 '15 at 19:10

























                                                                                                      answered Jul 6 '15 at 18:59









                                                                                                      Matt FargusonMatt Farguson

                                                                                                      22526




                                                                                                      22526























                                                                                                          1














                                                                                                          Another RegEx-based solution (untested):



                                                                                                          int NthIndexOf(string s, char t, int n) {
                                                                                                          if(n < 0) { throw new ArgumentException(); }
                                                                                                          if(n==1) { return s.IndexOf(t); }
                                                                                                          if(t=="") { return 0; }
                                                                                                          string et = RegEx.Escape(t);
                                                                                                          string pat = "(?<="
                                                                                                          + Microsoft.VisualBasic.StrDup(n-1, et + @"[.n]*") + ")"
                                                                                                          + et;
                                                                                                          Match m = RegEx.Match(s, pat);
                                                                                                          return m.Success ? m.Index : -1;
                                                                                                          }


                                                                                                          This should be slightly more optimal than requiring RegEx to create a Matches collection, only to discard all but one match.






                                                                                                          share|improve this answer
























                                                                                                          • In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                            – Ahmad Mageed
                                                                                                            Apr 3 '10 at 18:17
















                                                                                                          1














                                                                                                          Another RegEx-based solution (untested):



                                                                                                          int NthIndexOf(string s, char t, int n) {
                                                                                                          if(n < 0) { throw new ArgumentException(); }
                                                                                                          if(n==1) { return s.IndexOf(t); }
                                                                                                          if(t=="") { return 0; }
                                                                                                          string et = RegEx.Escape(t);
                                                                                                          string pat = "(?<="
                                                                                                          + Microsoft.VisualBasic.StrDup(n-1, et + @"[.n]*") + ")"
                                                                                                          + et;
                                                                                                          Match m = RegEx.Match(s, pat);
                                                                                                          return m.Success ? m.Index : -1;
                                                                                                          }


                                                                                                          This should be slightly more optimal than requiring RegEx to create a Matches collection, only to discard all but one match.






                                                                                                          share|improve this answer
























                                                                                                          • In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                            – Ahmad Mageed
                                                                                                            Apr 3 '10 at 18:17














                                                                                                          1












                                                                                                          1








                                                                                                          1







                                                                                                          Another RegEx-based solution (untested):



                                                                                                          int NthIndexOf(string s, char t, int n) {
                                                                                                          if(n < 0) { throw new ArgumentException(); }
                                                                                                          if(n==1) { return s.IndexOf(t); }
                                                                                                          if(t=="") { return 0; }
                                                                                                          string et = RegEx.Escape(t);
                                                                                                          string pat = "(?<="
                                                                                                          + Microsoft.VisualBasic.StrDup(n-1, et + @"[.n]*") + ")"
                                                                                                          + et;
                                                                                                          Match m = RegEx.Match(s, pat);
                                                                                                          return m.Success ? m.Index : -1;
                                                                                                          }


                                                                                                          This should be slightly more optimal than requiring RegEx to create a Matches collection, only to discard all but one match.






                                                                                                          share|improve this answer













                                                                                                          Another RegEx-based solution (untested):



                                                                                                          int NthIndexOf(string s, char t, int n) {
                                                                                                          if(n < 0) { throw new ArgumentException(); }
                                                                                                          if(n==1) { return s.IndexOf(t); }
                                                                                                          if(t=="") { return 0; }
                                                                                                          string et = RegEx.Escape(t);
                                                                                                          string pat = "(?<="
                                                                                                          + Microsoft.VisualBasic.StrDup(n-1, et + @"[.n]*") + ")"
                                                                                                          + et;
                                                                                                          Match m = RegEx.Match(s, pat);
                                                                                                          return m.Success ? m.Index : -1;
                                                                                                          }


                                                                                                          This should be slightly more optimal than requiring RegEx to create a Matches collection, only to discard all but one match.







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Apr 3 '10 at 17:50









                                                                                                          richardtallentrichardtallent

                                                                                                          24.7k1370106




                                                                                                          24.7k1370106













                                                                                                          • In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                            – Ahmad Mageed
                                                                                                            Apr 3 '10 at 18:17



















                                                                                                          • In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                            – Ahmad Mageed
                                                                                                            Apr 3 '10 at 18:17

















                                                                                                          In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                          – Ahmad Mageed
                                                                                                          Apr 3 '10 at 18:17





                                                                                                          In response to the Matches collection comment (since that is what I had shown in my response): I suppose a more efficient approach would be to use a while loop checking for match.Success and get the NextMatch while incrementing a counter and breaking early when the counter == index.

                                                                                                          – Ahmad Mageed
                                                                                                          Apr 3 '10 at 18:17











                                                                                                          1














                                                                                                              public static int FindOccuranceOf(this string str,char @char, int occurance)
                                                                                                          {
                                                                                                          var result = str.Select((x, y) => new { Letter = x, Index = y })
                                                                                                          .Where(letter => letter.Letter == @char).ToList();
                                                                                                          if (occurence > result.Count || occurance <= 0)
                                                                                                          {
                                                                                                          throw new IndexOutOfRangeException("occurance");
                                                                                                          }
                                                                                                          return result[occurance-1].Index ;
                                                                                                          }





                                                                                                          share|improve this answer






























                                                                                                            1














                                                                                                                public static int FindOccuranceOf(this string str,char @char, int occurance)
                                                                                                            {
                                                                                                            var result = str.Select((x, y) => new { Letter = x, Index = y })
                                                                                                            .Where(letter => letter.Letter == @char).ToList();
                                                                                                            if (occurence > result.Count || occurance <= 0)
                                                                                                            {
                                                                                                            throw new IndexOutOfRangeException("occurance");
                                                                                                            }
                                                                                                            return result[occurance-1].Index ;
                                                                                                            }





                                                                                                            share|improve this answer




























                                                                                                              1












                                                                                                              1








                                                                                                              1







                                                                                                                  public static int FindOccuranceOf(this string str,char @char, int occurance)
                                                                                                              {
                                                                                                              var result = str.Select((x, y) => new { Letter = x, Index = y })
                                                                                                              .Where(letter => letter.Letter == @char).ToList();
                                                                                                              if (occurence > result.Count || occurance <= 0)
                                                                                                              {
                                                                                                              throw new IndexOutOfRangeException("occurance");
                                                                                                              }
                                                                                                              return result[occurance-1].Index ;
                                                                                                              }





                                                                                                              share|improve this answer















                                                                                                                  public static int FindOccuranceOf(this string str,char @char, int occurance)
                                                                                                              {
                                                                                                              var result = str.Select((x, y) => new { Letter = x, Index = y })
                                                                                                              .Where(letter => letter.Letter == @char).ToList();
                                                                                                              if (occurence > result.Count || occurance <= 0)
                                                                                                              {
                                                                                                              throw new IndexOutOfRangeException("occurance");
                                                                                                              }
                                                                                                              return result[occurance-1].Index ;
                                                                                                              }






                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Apr 3 '10 at 19:18

























                                                                                                              answered Apr 3 '10 at 18:56









                                                                                                              Islam YahiateneIslam Yahiatene

                                                                                                              1,1161026




                                                                                                              1,1161026























                                                                                                                  1














                                                                                                                  Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.



                                                                                                                  public static int NthIndexOf(string text, char searchChar, int nthindex)
                                                                                                                  {
                                                                                                                  int index = -1;
                                                                                                                  try
                                                                                                                  {
                                                                                                                  var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
                                                                                                                  if (takeCount < text.Length) index = takeCount;
                                                                                                                  }
                                                                                                                  catch { }
                                                                                                                  return index;
                                                                                                                  }
                                                                                                                  public static int NthIndexOf(string text, string searchText, int nthindex)
                                                                                                                  {
                                                                                                                  int index = -1;
                                                                                                                  try
                                                                                                                  {
                                                                                                                  Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
                                                                                                                  if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
                                                                                                                  }
                                                                                                                  catch { }
                                                                                                                  return index;
                                                                                                                  }





                                                                                                                  share|improve this answer






























                                                                                                                    1














                                                                                                                    Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.



                                                                                                                    public static int NthIndexOf(string text, char searchChar, int nthindex)
                                                                                                                    {
                                                                                                                    int index = -1;
                                                                                                                    try
                                                                                                                    {
                                                                                                                    var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
                                                                                                                    if (takeCount < text.Length) index = takeCount;
                                                                                                                    }
                                                                                                                    catch { }
                                                                                                                    return index;
                                                                                                                    }
                                                                                                                    public static int NthIndexOf(string text, string searchText, int nthindex)
                                                                                                                    {
                                                                                                                    int index = -1;
                                                                                                                    try
                                                                                                                    {
                                                                                                                    Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
                                                                                                                    if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
                                                                                                                    }
                                                                                                                    catch { }
                                                                                                                    return index;
                                                                                                                    }





                                                                                                                    share|improve this answer




























                                                                                                                      1












                                                                                                                      1








                                                                                                                      1







                                                                                                                      Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.



                                                                                                                      public static int NthIndexOf(string text, char searchChar, int nthindex)
                                                                                                                      {
                                                                                                                      int index = -1;
                                                                                                                      try
                                                                                                                      {
                                                                                                                      var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
                                                                                                                      if (takeCount < text.Length) index = takeCount;
                                                                                                                      }
                                                                                                                      catch { }
                                                                                                                      return index;
                                                                                                                      }
                                                                                                                      public static int NthIndexOf(string text, string searchText, int nthindex)
                                                                                                                      {
                                                                                                                      int index = -1;
                                                                                                                      try
                                                                                                                      {
                                                                                                                      Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
                                                                                                                      if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
                                                                                                                      }
                                                                                                                      catch { }
                                                                                                                      return index;
                                                                                                                      }





                                                                                                                      share|improve this answer















                                                                                                                      Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.



                                                                                                                      public static int NthIndexOf(string text, char searchChar, int nthindex)
                                                                                                                      {
                                                                                                                      int index = -1;
                                                                                                                      try
                                                                                                                      {
                                                                                                                      var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
                                                                                                                      if (takeCount < text.Length) index = takeCount;
                                                                                                                      }
                                                                                                                      catch { }
                                                                                                                      return index;
                                                                                                                      }
                                                                                                                      public static int NthIndexOf(string text, string searchText, int nthindex)
                                                                                                                      {
                                                                                                                      int index = -1;
                                                                                                                      try
                                                                                                                      {
                                                                                                                      Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
                                                                                                                      if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
                                                                                                                      }
                                                                                                                      catch { }
                                                                                                                      return index;
                                                                                                                      }






                                                                                                                      share|improve this answer














                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer








                                                                                                                      edited Jun 18 '12 at 10:33









                                                                                                                      Hans Olsson

                                                                                                                      44.3k1278103




                                                                                                                      44.3k1278103










                                                                                                                      answered Jun 18 '12 at 10:17









                                                                                                                      Suneel GuptaSuneel Gupta

                                                                                                                      39937




                                                                                                                      39937























                                                                                                                          1














                                                                                                                          Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):



                                                                                                                          public static int NthIndexOf(this string input, char value, int n)
                                                                                                                          {
                                                                                                                          if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                          int i = -1;
                                                                                                                          do
                                                                                                                          {
                                                                                                                          i = input.IndexOf(value, i + 1);
                                                                                                                          n--;
                                                                                                                          }
                                                                                                                          while (i != -1 && n > 0);

                                                                                                                          return i;
                                                                                                                          }


                                                                                                                          Or to search from the end of the string using LastIndexOf:



                                                                                                                          public static int NthLastIndexOf(this string input, char value, int n)
                                                                                                                          {
                                                                                                                          if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                          int i = input.Length;
                                                                                                                          do
                                                                                                                          {
                                                                                                                          i = input.LastIndexOf(value, i - 1);
                                                                                                                          n--;
                                                                                                                          }
                                                                                                                          while (i != -1 && n > 0);

                                                                                                                          return i;
                                                                                                                          }


                                                                                                                          Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.






                                                                                                                          share|improve this answer




























                                                                                                                            1














                                                                                                                            Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):



                                                                                                                            public static int NthIndexOf(this string input, char value, int n)
                                                                                                                            {
                                                                                                                            if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                            int i = -1;
                                                                                                                            do
                                                                                                                            {
                                                                                                                            i = input.IndexOf(value, i + 1);
                                                                                                                            n--;
                                                                                                                            }
                                                                                                                            while (i != -1 && n > 0);

                                                                                                                            return i;
                                                                                                                            }


                                                                                                                            Or to search from the end of the string using LastIndexOf:



                                                                                                                            public static int NthLastIndexOf(this string input, char value, int n)
                                                                                                                            {
                                                                                                                            if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                            int i = input.Length;
                                                                                                                            do
                                                                                                                            {
                                                                                                                            i = input.LastIndexOf(value, i - 1);
                                                                                                                            n--;
                                                                                                                            }
                                                                                                                            while (i != -1 && n > 0);

                                                                                                                            return i;
                                                                                                                            }


                                                                                                                            Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.






                                                                                                                            share|improve this answer


























                                                                                                                              1












                                                                                                                              1








                                                                                                                              1







                                                                                                                              Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):



                                                                                                                              public static int NthIndexOf(this string input, char value, int n)
                                                                                                                              {
                                                                                                                              if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                              int i = -1;
                                                                                                                              do
                                                                                                                              {
                                                                                                                              i = input.IndexOf(value, i + 1);
                                                                                                                              n--;
                                                                                                                              }
                                                                                                                              while (i != -1 && n > 0);

                                                                                                                              return i;
                                                                                                                              }


                                                                                                                              Or to search from the end of the string using LastIndexOf:



                                                                                                                              public static int NthLastIndexOf(this string input, char value, int n)
                                                                                                                              {
                                                                                                                              if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                              int i = input.Length;
                                                                                                                              do
                                                                                                                              {
                                                                                                                              i = input.LastIndexOf(value, i - 1);
                                                                                                                              n--;
                                                                                                                              }
                                                                                                                              while (i != -1 && n > 0);

                                                                                                                              return i;
                                                                                                                              }


                                                                                                                              Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.






                                                                                                                              share|improve this answer













                                                                                                                              Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):



                                                                                                                              public static int NthIndexOf(this string input, char value, int n)
                                                                                                                              {
                                                                                                                              if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                              int i = -1;
                                                                                                                              do
                                                                                                                              {
                                                                                                                              i = input.IndexOf(value, i + 1);
                                                                                                                              n--;
                                                                                                                              }
                                                                                                                              while (i != -1 && n > 0);

                                                                                                                              return i;
                                                                                                                              }


                                                                                                                              Or to search from the end of the string using LastIndexOf:



                                                                                                                              public static int NthLastIndexOf(this string input, char value, int n)
                                                                                                                              {
                                                                                                                              if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

                                                                                                                              int i = input.Length;
                                                                                                                              do
                                                                                                                              {
                                                                                                                              i = input.LastIndexOf(value, i - 1);
                                                                                                                              n--;
                                                                                                                              }
                                                                                                                              while (i != -1 && n > 0);

                                                                                                                              return i;
                                                                                                                              }


                                                                                                                              Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.







                                                                                                                              share|improve this answer












                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer










                                                                                                                              answered Feb 12 '14 at 15:01









                                                                                                                              RonaldRonald

                                                                                                                              1,5071313




                                                                                                                              1,5071313























                                                                                                                                  1














                                                                                                                                  Marc Cals' LINQ Extended for generic.



                                                                                                                                     using System;
                                                                                                                                  using System.Collections.Generic;
                                                                                                                                  using System.Linq;

                                                                                                                                  namespace fNns
                                                                                                                                  {
                                                                                                                                  public class indexer<T> where T : IEquatable<T>
                                                                                                                                  {
                                                                                                                                  public T t { get; set; }
                                                                                                                                  public int index { get; set; }
                                                                                                                                  }
                                                                                                                                  public static class fN
                                                                                                                                  {
                                                                                                                                  public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
                                                                                                                                  int occurrencePosition) where T : IEquatable<T>
                                                                                                                                  {
                                                                                                                                  var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                                                                                                                                  .Where(item => item.t.Equals(t))
                                                                                                                                  .Skip(occurrencePosition - 1)
                                                                                                                                  .FirstOrDefault();
                                                                                                                                  return result;
                                                                                                                                  }
                                                                                                                                  public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
                                                                                                                                  int occurrencePosition) where T : IEquatable<T>
                                                                                                                                  {
                                                                                                                                  var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                                                                                                                                  .Where(item => item.t.Equals(t))
                                                                                                                                  .Skip(occurrencePosition - 1)
                                                                                                                                  .FirstOrDefault();
                                                                                                                                  return result;
                                                                                                                                  }
                                                                                                                                  }
                                                                                                                                  }


                                                                                                                                  Some tests.



                                                                                                                                     using System;
                                                                                                                                  using System.Collections.Generic;
                                                                                                                                  using NUnit.Framework;
                                                                                                                                  using Newtonsoft.Json;
                                                                                                                                  namespace FindNthNamespace.Tests
                                                                                                                                  {

                                                                                                                                  public class fNTests
                                                                                                                                  {
                                                                                                                                  [TestCase("pass", "dtststx", 't', 3, Result = "{"t":"t","index":5}")]
                                                                                                                                  [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                  0, 2, Result="{"t":0,"index":10}")]
                                                                                                                                  public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                  {
                                                                                                                                  Console.WriteLine(scenario);
                                                                                                                                  return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                  }

                                                                                                                                  [TestCase("pass", "dtststxx", 't', 3, Result = "{"t":"t","index":6}")]
                                                                                                                                  [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                  0, 2, Result = "{"t":0,"index":19}")]
                                                                                                                                  public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                  {
                                                                                                                                  Console.WriteLine(scenario);
                                                                                                                                  return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                  }


                                                                                                                                  }


                                                                                                                                  }






                                                                                                                                  share|improve this answer






























                                                                                                                                    1














                                                                                                                                    Marc Cals' LINQ Extended for generic.



                                                                                                                                       using System;
                                                                                                                                    using System.Collections.Generic;
                                                                                                                                    using System.Linq;

                                                                                                                                    namespace fNns
                                                                                                                                    {
                                                                                                                                    public class indexer<T> where T : IEquatable<T>
                                                                                                                                    {
                                                                                                                                    public T t { get; set; }
                                                                                                                                    public int index { get; set; }
                                                                                                                                    }
                                                                                                                                    public static class fN
                                                                                                                                    {
                                                                                                                                    public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
                                                                                                                                    int occurrencePosition) where T : IEquatable<T>
                                                                                                                                    {
                                                                                                                                    var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                                                                                                                                    .Where(item => item.t.Equals(t))
                                                                                                                                    .Skip(occurrencePosition - 1)
                                                                                                                                    .FirstOrDefault();
                                                                                                                                    return result;
                                                                                                                                    }
                                                                                                                                    public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
                                                                                                                                    int occurrencePosition) where T : IEquatable<T>
                                                                                                                                    {
                                                                                                                                    var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                                                                                                                                    .Where(item => item.t.Equals(t))
                                                                                                                                    .Skip(occurrencePosition - 1)
                                                                                                                                    .FirstOrDefault();
                                                                                                                                    return result;
                                                                                                                                    }
                                                                                                                                    }
                                                                                                                                    }


                                                                                                                                    Some tests.



                                                                                                                                       using System;
                                                                                                                                    using System.Collections.Generic;
                                                                                                                                    using NUnit.Framework;
                                                                                                                                    using Newtonsoft.Json;
                                                                                                                                    namespace FindNthNamespace.Tests
                                                                                                                                    {

                                                                                                                                    public class fNTests
                                                                                                                                    {
                                                                                                                                    [TestCase("pass", "dtststx", 't', 3, Result = "{"t":"t","index":5}")]
                                                                                                                                    [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                    0, 2, Result="{"t":0,"index":10}")]
                                                                                                                                    public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                    {
                                                                                                                                    Console.WriteLine(scenario);
                                                                                                                                    return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                    }

                                                                                                                                    [TestCase("pass", "dtststxx", 't', 3, Result = "{"t":"t","index":6}")]
                                                                                                                                    [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                    0, 2, Result = "{"t":0,"index":19}")]
                                                                                                                                    public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                    {
                                                                                                                                    Console.WriteLine(scenario);
                                                                                                                                    return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                    }


                                                                                                                                    }


                                                                                                                                    }






                                                                                                                                    share|improve this answer




























                                                                                                                                      1












                                                                                                                                      1








                                                                                                                                      1







                                                                                                                                      Marc Cals' LINQ Extended for generic.



                                                                                                                                         using System;
                                                                                                                                      using System.Collections.Generic;
                                                                                                                                      using System.Linq;

                                                                                                                                      namespace fNns
                                                                                                                                      {
                                                                                                                                      public class indexer<T> where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      public T t { get; set; }
                                                                                                                                      public int index { get; set; }
                                                                                                                                      }
                                                                                                                                      public static class fN
                                                                                                                                      {
                                                                                                                                      public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
                                                                                                                                      int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                                                                                                                                      .Where(item => item.t.Equals(t))
                                                                                                                                      .Skip(occurrencePosition - 1)
                                                                                                                                      .FirstOrDefault();
                                                                                                                                      return result;
                                                                                                                                      }
                                                                                                                                      public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
                                                                                                                                      int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                                                                                                                                      .Where(item => item.t.Equals(t))
                                                                                                                                      .Skip(occurrencePosition - 1)
                                                                                                                                      .FirstOrDefault();
                                                                                                                                      return result;
                                                                                                                                      }
                                                                                                                                      }
                                                                                                                                      }


                                                                                                                                      Some tests.



                                                                                                                                         using System;
                                                                                                                                      using System.Collections.Generic;
                                                                                                                                      using NUnit.Framework;
                                                                                                                                      using Newtonsoft.Json;
                                                                                                                                      namespace FindNthNamespace.Tests
                                                                                                                                      {

                                                                                                                                      public class fNTests
                                                                                                                                      {
                                                                                                                                      [TestCase("pass", "dtststx", 't', 3, Result = "{"t":"t","index":5}")]
                                                                                                                                      [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                      0, 2, Result="{"t":0,"index":10}")]
                                                                                                                                      public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      Console.WriteLine(scenario);
                                                                                                                                      return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                      }

                                                                                                                                      [TestCase("pass", "dtststxx", 't', 3, Result = "{"t":"t","index":6}")]
                                                                                                                                      [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                      0, 2, Result = "{"t":0,"index":19}")]
                                                                                                                                      public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      Console.WriteLine(scenario);
                                                                                                                                      return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                      }


                                                                                                                                      }


                                                                                                                                      }






                                                                                                                                      share|improve this answer















                                                                                                                                      Marc Cals' LINQ Extended for generic.



                                                                                                                                         using System;
                                                                                                                                      using System.Collections.Generic;
                                                                                                                                      using System.Linq;

                                                                                                                                      namespace fNns
                                                                                                                                      {
                                                                                                                                      public class indexer<T> where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      public T t { get; set; }
                                                                                                                                      public int index { get; set; }
                                                                                                                                      }
                                                                                                                                      public static class fN
                                                                                                                                      {
                                                                                                                                      public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
                                                                                                                                      int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                                                                                                                                      .Where(item => item.t.Equals(t))
                                                                                                                                      .Skip(occurrencePosition - 1)
                                                                                                                                      .FirstOrDefault();
                                                                                                                                      return result;
                                                                                                                                      }
                                                                                                                                      public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
                                                                                                                                      int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                                                                                                                                      .Where(item => item.t.Equals(t))
                                                                                                                                      .Skip(occurrencePosition - 1)
                                                                                                                                      .FirstOrDefault();
                                                                                                                                      return result;
                                                                                                                                      }
                                                                                                                                      }
                                                                                                                                      }


                                                                                                                                      Some tests.



                                                                                                                                         using System;
                                                                                                                                      using System.Collections.Generic;
                                                                                                                                      using NUnit.Framework;
                                                                                                                                      using Newtonsoft.Json;
                                                                                                                                      namespace FindNthNamespace.Tests
                                                                                                                                      {

                                                                                                                                      public class fNTests
                                                                                                                                      {
                                                                                                                                      [TestCase("pass", "dtststx", 't', 3, Result = "{"t":"t","index":5}")]
                                                                                                                                      [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                      0, 2, Result="{"t":0,"index":10}")]
                                                                                                                                      public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      Console.WriteLine(scenario);
                                                                                                                                      return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                      }

                                                                                                                                      [TestCase("pass", "dtststxx", 't', 3, Result = "{"t":"t","index":6}")]
                                                                                                                                      [TestCase("pass", new int { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                                                                                                                                      0, 2, Result = "{"t":0,"index":19}")]
                                                                                                                                      public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
                                                                                                                                      {
                                                                                                                                      Console.WriteLine(scenario);
                                                                                                                                      return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
                                                                                                                                      }


                                                                                                                                      }


                                                                                                                                      }







                                                                                                                                      share|improve this answer














                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer








                                                                                                                                      edited Jun 29 '15 at 19:42

























                                                                                                                                      answered Jun 28 '15 at 20:04









                                                                                                                                      user2584621user2584621

                                                                                                                                      475168




                                                                                                                                      475168























                                                                                                                                          1














                                                                                                                                          Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.



                                                                                                                                          Here's the string match version:



                                                                                                                                          public static int IndexOfNth(this string source, string matchString, 
                                                                                                                                          int charInstance,
                                                                                                                                          StringComparison stringComparison = StringComparison.CurrentCulture)
                                                                                                                                          {
                                                                                                                                          if (string.IsNullOrEmpty(source))
                                                                                                                                          return -1;

                                                                                                                                          int lastPos = 0;
                                                                                                                                          int count = 0;

                                                                                                                                          while (count < charInstance )
                                                                                                                                          {
                                                                                                                                          var len = source.Length - lastPos;
                                                                                                                                          lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
                                                                                                                                          if (lastPos == -1)
                                                                                                                                          break;

                                                                                                                                          count++;
                                                                                                                                          if (count == charInstance)
                                                                                                                                          return lastPos;

                                                                                                                                          lastPos += matchString.Length;
                                                                                                                                          }
                                                                                                                                          return -1;
                                                                                                                                          }


                                                                                                                                          and the char match version:



                                                                                                                                          public static int IndexOfNth(string source, char matchChar, int charInstance)        
                                                                                                                                          {
                                                                                                                                          if (string.IsNullOrEmpty(source))
                                                                                                                                          return -1;

                                                                                                                                          if (charInstance < 1)
                                                                                                                                          return -1;

                                                                                                                                          int count = 0;
                                                                                                                                          for (int i = 0; i < source.Length; i++)
                                                                                                                                          {
                                                                                                                                          if (source[i] == matchChar)
                                                                                                                                          {
                                                                                                                                          count++;
                                                                                                                                          if (count == charInstance)
                                                                                                                                          return i;
                                                                                                                                          }
                                                                                                                                          }
                                                                                                                                          return -1;
                                                                                                                                          }


                                                                                                                                          I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.






                                                                                                                                          share|improve this answer




























                                                                                                                                            1














                                                                                                                                            Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.



                                                                                                                                            Here's the string match version:



                                                                                                                                            public static int IndexOfNth(this string source, string matchString, 
                                                                                                                                            int charInstance,
                                                                                                                                            StringComparison stringComparison = StringComparison.CurrentCulture)
                                                                                                                                            {
                                                                                                                                            if (string.IsNullOrEmpty(source))
                                                                                                                                            return -1;

                                                                                                                                            int lastPos = 0;
                                                                                                                                            int count = 0;

                                                                                                                                            while (count < charInstance )
                                                                                                                                            {
                                                                                                                                            var len = source.Length - lastPos;
                                                                                                                                            lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
                                                                                                                                            if (lastPos == -1)
                                                                                                                                            break;

                                                                                                                                            count++;
                                                                                                                                            if (count == charInstance)
                                                                                                                                            return lastPos;

                                                                                                                                            lastPos += matchString.Length;
                                                                                                                                            }
                                                                                                                                            return -1;
                                                                                                                                            }


                                                                                                                                            and the char match version:



                                                                                                                                            public static int IndexOfNth(string source, char matchChar, int charInstance)        
                                                                                                                                            {
                                                                                                                                            if (string.IsNullOrEmpty(source))
                                                                                                                                            return -1;

                                                                                                                                            if (charInstance < 1)
                                                                                                                                            return -1;

                                                                                                                                            int count = 0;
                                                                                                                                            for (int i = 0; i < source.Length; i++)
                                                                                                                                            {
                                                                                                                                            if (source[i] == matchChar)
                                                                                                                                            {
                                                                                                                                            count++;
                                                                                                                                            if (count == charInstance)
                                                                                                                                            return i;
                                                                                                                                            }
                                                                                                                                            }
                                                                                                                                            return -1;
                                                                                                                                            }


                                                                                                                                            I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.






                                                                                                                                            share|improve this answer


























                                                                                                                                              1












                                                                                                                                              1








                                                                                                                                              1







                                                                                                                                              Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.



                                                                                                                                              Here's the string match version:



                                                                                                                                              public static int IndexOfNth(this string source, string matchString, 
                                                                                                                                              int charInstance,
                                                                                                                                              StringComparison stringComparison = StringComparison.CurrentCulture)
                                                                                                                                              {
                                                                                                                                              if (string.IsNullOrEmpty(source))
                                                                                                                                              return -1;

                                                                                                                                              int lastPos = 0;
                                                                                                                                              int count = 0;

                                                                                                                                              while (count < charInstance )
                                                                                                                                              {
                                                                                                                                              var len = source.Length - lastPos;
                                                                                                                                              lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
                                                                                                                                              if (lastPos == -1)
                                                                                                                                              break;

                                                                                                                                              count++;
                                                                                                                                              if (count == charInstance)
                                                                                                                                              return lastPos;

                                                                                                                                              lastPos += matchString.Length;
                                                                                                                                              }
                                                                                                                                              return -1;
                                                                                                                                              }


                                                                                                                                              and the char match version:



                                                                                                                                              public static int IndexOfNth(string source, char matchChar, int charInstance)        
                                                                                                                                              {
                                                                                                                                              if (string.IsNullOrEmpty(source))
                                                                                                                                              return -1;

                                                                                                                                              if (charInstance < 1)
                                                                                                                                              return -1;

                                                                                                                                              int count = 0;
                                                                                                                                              for (int i = 0; i < source.Length; i++)
                                                                                                                                              {
                                                                                                                                              if (source[i] == matchChar)
                                                                                                                                              {
                                                                                                                                              count++;
                                                                                                                                              if (count == charInstance)
                                                                                                                                              return i;
                                                                                                                                              }
                                                                                                                                              }
                                                                                                                                              return -1;
                                                                                                                                              }


                                                                                                                                              I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.






                                                                                                                                              share|improve this answer













                                                                                                                                              Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.



                                                                                                                                              Here's the string match version:



                                                                                                                                              public static int IndexOfNth(this string source, string matchString, 
                                                                                                                                              int charInstance,
                                                                                                                                              StringComparison stringComparison = StringComparison.CurrentCulture)
                                                                                                                                              {
                                                                                                                                              if (string.IsNullOrEmpty(source))
                                                                                                                                              return -1;

                                                                                                                                              int lastPos = 0;
                                                                                                                                              int count = 0;

                                                                                                                                              while (count < charInstance )
                                                                                                                                              {
                                                                                                                                              var len = source.Length - lastPos;
                                                                                                                                              lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
                                                                                                                                              if (lastPos == -1)
                                                                                                                                              break;

                                                                                                                                              count++;
                                                                                                                                              if (count == charInstance)
                                                                                                                                              return lastPos;

                                                                                                                                              lastPos += matchString.Length;
                                                                                                                                              }
                                                                                                                                              return -1;
                                                                                                                                              }


                                                                                                                                              and the char match version:



                                                                                                                                              public static int IndexOfNth(string source, char matchChar, int charInstance)        
                                                                                                                                              {
                                                                                                                                              if (string.IsNullOrEmpty(source))
                                                                                                                                              return -1;

                                                                                                                                              if (charInstance < 1)
                                                                                                                                              return -1;

                                                                                                                                              int count = 0;
                                                                                                                                              for (int i = 0; i < source.Length; i++)
                                                                                                                                              {
                                                                                                                                              if (source[i] == matchChar)
                                                                                                                                              {
                                                                                                                                              count++;
                                                                                                                                              if (count == charInstance)
                                                                                                                                              return i;
                                                                                                                                              }
                                                                                                                                              }
                                                                                                                                              return -1;
                                                                                                                                              }


                                                                                                                                              I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.







                                                                                                                                              share|improve this answer












                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer










                                                                                                                                              answered Jun 10 '18 at 23:09









                                                                                                                                              Rick StrahlRick Strahl

                                                                                                                                              10.6k96197




                                                                                                                                              10.6k96197























                                                                                                                                                  0














                                                                                                                                                  string theString = "The String";
                                                                                                                                                  int index = theString.NthIndexOf("THEVALUE", 3, true);





                                                                                                                                                  share|improve this answer




























                                                                                                                                                    0














                                                                                                                                                    string theString = "The String";
                                                                                                                                                    int index = theString.NthIndexOf("THEVALUE", 3, true);





                                                                                                                                                    share|improve this answer


























                                                                                                                                                      0












                                                                                                                                                      0








                                                                                                                                                      0







                                                                                                                                                      string theString = "The String";
                                                                                                                                                      int index = theString.NthIndexOf("THEVALUE", 3, true);





                                                                                                                                                      share|improve this answer













                                                                                                                                                      string theString = "The String";
                                                                                                                                                      int index = theString.NthIndexOf("THEVALUE", 3, true);






                                                                                                                                                      share|improve this answer












                                                                                                                                                      share|improve this answer



                                                                                                                                                      share|improve this answer










                                                                                                                                                      answered Oct 25 '18 at 16:48









                                                                                                                                                      VersatileVersatile

                                                                                                                                                      443512




                                                                                                                                                      443512























                                                                                                                                                          0














                                                                                                                                                          public static int IndexOfAny(this string str, string values, int startIndex, out string selectedItem)
                                                                                                                                                          {
                                                                                                                                                          int first = -1;
                                                                                                                                                          selectedItem = null;
                                                                                                                                                          foreach (string item in values)
                                                                                                                                                          {
                                                                                                                                                          int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
                                                                                                                                                          if (i >= 0)
                                                                                                                                                          {
                                                                                                                                                          if (first > 0)
                                                                                                                                                          {
                                                                                                                                                          if (i < first)
                                                                                                                                                          {
                                                                                                                                                          first = i;
                                                                                                                                                          selectedItem = item;
                                                                                                                                                          }
                                                                                                                                                          }
                                                                                                                                                          else
                                                                                                                                                          {
                                                                                                                                                          first = i;
                                                                                                                                                          selectedItem = item;
                                                                                                                                                          }
                                                                                                                                                          }
                                                                                                                                                          }
                                                                                                                                                          return first;
                                                                                                                                                          }





                                                                                                                                                          share|improve this answer




























                                                                                                                                                            0














                                                                                                                                                            public static int IndexOfAny(this string str, string values, int startIndex, out string selectedItem)
                                                                                                                                                            {
                                                                                                                                                            int first = -1;
                                                                                                                                                            selectedItem = null;
                                                                                                                                                            foreach (string item in values)
                                                                                                                                                            {
                                                                                                                                                            int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
                                                                                                                                                            if (i >= 0)
                                                                                                                                                            {
                                                                                                                                                            if (first > 0)
                                                                                                                                                            {
                                                                                                                                                            if (i < first)
                                                                                                                                                            {
                                                                                                                                                            first = i;
                                                                                                                                                            selectedItem = item;
                                                                                                                                                            }
                                                                                                                                                            }
                                                                                                                                                            else
                                                                                                                                                            {
                                                                                                                                                            first = i;
                                                                                                                                                            selectedItem = item;
                                                                                                                                                            }
                                                                                                                                                            }
                                                                                                                                                            }
                                                                                                                                                            return first;
                                                                                                                                                            }





                                                                                                                                                            share|improve this answer


























                                                                                                                                                              0












                                                                                                                                                              0








                                                                                                                                                              0







                                                                                                                                                              public static int IndexOfAny(this string str, string values, int startIndex, out string selectedItem)
                                                                                                                                                              {
                                                                                                                                                              int first = -1;
                                                                                                                                                              selectedItem = null;
                                                                                                                                                              foreach (string item in values)
                                                                                                                                                              {
                                                                                                                                                              int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
                                                                                                                                                              if (i >= 0)
                                                                                                                                                              {
                                                                                                                                                              if (first > 0)
                                                                                                                                                              {
                                                                                                                                                              if (i < first)
                                                                                                                                                              {
                                                                                                                                                              first = i;
                                                                                                                                                              selectedItem = item;
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              else
                                                                                                                                                              {
                                                                                                                                                              first = i;
                                                                                                                                                              selectedItem = item;
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              return first;
                                                                                                                                                              }





                                                                                                                                                              share|improve this answer













                                                                                                                                                              public static int IndexOfAny(this string str, string values, int startIndex, out string selectedItem)
                                                                                                                                                              {
                                                                                                                                                              int first = -1;
                                                                                                                                                              selectedItem = null;
                                                                                                                                                              foreach (string item in values)
                                                                                                                                                              {
                                                                                                                                                              int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
                                                                                                                                                              if (i >= 0)
                                                                                                                                                              {
                                                                                                                                                              if (first > 0)
                                                                                                                                                              {
                                                                                                                                                              if (i < first)
                                                                                                                                                              {
                                                                                                                                                              first = i;
                                                                                                                                                              selectedItem = item;
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              else
                                                                                                                                                              {
                                                                                                                                                              first = i;
                                                                                                                                                              selectedItem = item;
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              }
                                                                                                                                                              return first;
                                                                                                                                                              }






                                                                                                                                                              share|improve this answer












                                                                                                                                                              share|improve this answer



                                                                                                                                                              share|improve this answer










                                                                                                                                                              answered Nov 22 '18 at 10:23









                                                                                                                                                              Vahid BorandehVahid Borandeh

                                                                                                                                                              62




                                                                                                                                                              62






























                                                                                                                                                                  draft saved

                                                                                                                                                                  draft discarded




















































                                                                                                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                  But avoid



                                                                                                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                  To learn more, see our tips on writing great answers.




                                                                                                                                                                  draft saved


                                                                                                                                                                  draft discarded














                                                                                                                                                                  StackExchange.ready(
                                                                                                                                                                  function () {
                                                                                                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2571716%2ffind-nth-occurrence-of-a-character-in-a-string%23new-answer', 'question_page');
                                                                                                                                                                  }
                                                                                                                                                                  );

                                                                                                                                                                  Post as a guest















                                                                                                                                                                  Required, but never shown





















































                                                                                                                                                                  Required, but never shown














                                                                                                                                                                  Required, but never shown












                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Required, but never shown

































                                                                                                                                                                  Required, but never shown














                                                                                                                                                                  Required, but never shown












                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Required, but never shown







                                                                                                                                                                  Popular posts from this blog

                                                                                                                                                                  404 Error Contact Form 7 ajax form submitting

                                                                                                                                                                  How to know if a Active Directory user can login interactively

                                                                                                                                                                  Refactoring coordinates for Minecraft Pi buildings written in Python