Chapter Contents

Previous

Next
strcspn

strcspn



Locate the First Occurrence of the First Character in a Set

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <string.h>

size_t strcspn(const char *str, const char *cset);


DESCRIPTION

strcspn locates the first character in the first argument string ( str ) contained in the second argument string ( cset ), returning its position in the first argument.


RETURN VALUE

strcspn returns the number of consecutive characters not in the given character set found in the argument string, starting at the first character. If all characters of the string are not in the set (so that no character in the set can be found), the value returned is the length of the string. Similarly, if the character set is null (that is, if it contains no characters), the return value from strcspn is the length of the first argument.


CAUTION

A protection or addressing exception may occur if either argument is not properly terminated.

See the memscntb function description for information on possible interactions between the strcspn , memscntb , or strscntb functions.


EXAMPLE

#include <string.h>
#include <stdio.h>

#define MAXLINE 100

main()
{
   char text[MAXLINE+1];
   size_t pos, len;
   int words;
   for (;;) {
      puts("Enter a line of text.");
      puts("Just press Enter to quit.");
      gets(text);
      if (text[0] == '\0') exit(0); /* Quit if null input.     */
      pos = 0;
      words = 0;
      for (;;) {
            /* Skip to next punctuation mark.                  */
         len = strcspn(text+pos, " .,?!");
            /* if next character is punctuation                */
         if (len == 0) {
            ++pos;
            continue;               /* Skip to next character. */
         }
            /* encountered the end of the string */
         if (text[pos+len] == '\0') break;
         if (words == 0)
            puts("The words in the input line are:");
         ++words;
         do{
            putchar(text[pos]);
            ++pos;
         } while(--len);
         putchar('\n');
         ++pos;                     /* Skip the punctuation.   */
      }
   if (words == 0)
   puts("There were no words in that line.");
   }
}


RELATED FUNCTIONS

strrcspn , strscan , strspn


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.