Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find Nth Occurence of character

Status
Not open for further replies.

robertfah

Programmer
Mar 20, 2006
380
US
I've got a string in which I need to find the starting point of the 2nd underscore:

BBBB_BBBBB_20100101.doc

I am trying to extract BBBB_BBBBB from the file name. Is there a built in function that I can use that will search a string for the 2nd occurence of a character? Almost like IndexOf?
 
there is not a string.FindSecondIndexof(string) if that's what you're asking. building one wouldn't be difficult.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Will string.LastIndexOf() do what you want?
 
that would only work if there were exactly 2 underscores in the file name. if the file names follow the convention above it will work, other wise a string.IndexOf(string s, int occurance) will be required.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
How about using a regular expression with a pattern of "^[a-zA-Z0-9]+_[a-zA-Z0-9]+_"? The match returned will have the 2nd underscore so you will have to trim that off, but should work.
 
nice. wrap that in an extension method to encapsulate the regex and you could have a nice little NthIndexOf method
Code:
pubic static class StringExtensions
{
   public static int NthIndexOf(this string s, int occurrence)
   {
      const string part = @"[a-zA-Z0-9]+_";
      var pattern = new StringBuilder("^");
      while(occurrence> 0)
      {
         pattern.Append(part);
         occurrence--;
      }
      var match = Regex.Match(pattern.ToString());
      return match.Success ? match.Index : -1;
   }
}
or something like that. you can then us it like this
Code:
var index = "hi_my_name_is_jason".NthIndexOf(2);
//index = 5

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top