0

Hey guys what's the easiest way to find the Nth occurrence of a character in a string? I'm hoping there is a standard library function with a name like "NthOf" or something.

Thx.

2
Contributors
1
Reply
4
Views
6 Years
Discussion Span
Last Post by Momerath
1

There isn't, but I made one for you!

using System;
using System.Text.RegularExpressions;

namespace ExtensionMethods {
    static class Extensions {
        public static int NthOf(this String s, char c, int n) {
            int result = -1;
            MatchCollection mc = Regex.Matches(s, c.ToString());
            if (mc.Count >= n) {
                result = mc[n - 1].Index;
            }

            return result;
        }
    }
}

Put that in a file, and using Extensions; at the top of your program, and now you can say things like

String s = "this is a test string";
int p = s.NthOf('t', 3);

And it will tell you where the 3rd one is, or -1 if there isn't a 3rd one :)

Votes + Comments
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.