Saturday, January 30, 2010

StrSpn & StrCSpn in C#

After converting the c/c++ string tokenizing command strtok to c#, I thought I would look around to see there were any other interesting string commands in c/c++ that had not been integrated into c#. What I found was strspn and strcspn.

strspn (String Span) Returns the length of the longest substring that begins at the start of the string and consists only of the characters found in the supplied character array.

Code Snippet



  1. private int strspn(string InputString, char[] Mask)

  2. {

  3.     int count = 0;

  4.  

  5.     foreach (var c in InputString)

  6.     {

  7.         if (!Mask.Contains(c)) break;

  8.  

  9.         count++;

  10.     }

  11.     return count;

  12. }





strcspn (String Complement Span) Returns the length of the longest substring that begins at the start of the string and contains none of the characters found in the supplied character array.

Code Snippet



  1.     private int strcspn(string InputString, char[] Mask)

  2.     {

  3.         int count = 0;

  4.  

  5.         foreach (var c in InputString)

  6.         {

  7.             if (Mask.Contains(c)) break;

  8.  

  9.             count++;

  10.         }

  11.         return count;

  12.     }

  13. }



2 comments:

Anonymous said...

Thanks for this. I was looking for the strspn implementation. For the strcspn implementation, I am using:

InputString.IndexOfAny(Mask);

Won't that work?

Chris

Lee Saunders said...

Actually, it would.