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.

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

commented: Yay! +8
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.