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.
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 :)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.
You're trying to visit a URL that doesn't currently exist on the web. Most likely, a member posted a link a long time ago to a web page that has since been removed. It's also possible that there was a typo when posting the URL. We redirect you to this notice instead of stripping out the link to preserve the integrity of the post.