Okay, I hit the send before done button again...
int index = 0;
int count = 0;
while(index < testString) {
int indexOf = testString.IndexOf(splitString, index);
if ( indexOf != -1 ) {
count++; index = (indexOf + splitString.Length);
} else { index = testString.Length; }
}
That should get you the number of occurences correctly.
Also note that an issue in my original code didn't take into
account split string length for purposes of offseting. That
makes a big difference in the output of something like (match
all occurences of (aa) in (aaaa). Normally that should be two,
but my old method would have returned three. I guess that is
a highly ambiguous case.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog:
http://weblogs.asp.net/justin_rogers
"Justin Rogers" <Justin@games4dotnet.com> wrote in message
news:OsvrSYKLEHA.340@TK2MSFTNGP11.phx.gbl...[color=blue]
> Regular expressions are going to be slower.
>
> I wrote something a while back that stores the offset of all string
> occurences within another string. You can see that here:
>
http://weblogs.asp.net/justin_rogers.../14/89545.aspx
> The relavent code is in SplitByString and appears below as well.
>
> while(index < testString.Length) {
> int indexOf = testString.IndexOf(split, index);
> if ( indexOf != -1 ) {
> offsets[offset++] = indexOf;
> index = (indexOf+1);
> } else {
> index = testString.Length;
> }
> }
>
> Now, what about fixing that code up to just count?
>
>
> int index = 0;
> while(index < testString.Length) {
> int indexOf = testString.IndexOf(split, index);
> if ( indexOf != -1 ) {
> offsets[offset++] = indexOf;
> index = (indexOf+1);
> } else {
> index = testString.Length;
> }
> }
>
>
>
> "Jason Gleason" <jason.gleason@gensurvey.com> wrote in message
> news:%23RwZgkJLEHA.1144@TK2MSFTNGP12.phx.gbl...[color=green]
> > What's the most efficient way to get the number of occurences of a certain
> > string in another string..for instance i'm using the following code right
> > now...
> >
> > private int CharacterCounter(String text,String Character)
> >
> > {
> >
> > int count = 0;
> >
> > for (int i = 0; i < text.Length; i++)
> >
> > {
> >
> > if(text.Substring(i,1) == Character)
> >
> > {
> >
> > count++;
> >
> > }
> >
> > }
> >
> > return count;
> >
> > }
> >
> > The problem with this way is it's not the fastest doing big strings multiple
> > times over the course of a program run. Is there an easier/faster way to do
> > it using regular expressions?
> >
> >
> >
> >
> >
> >[/color]
>
>[/color]