Testing characters in a string with Character Classification Functions - C String

C examples for String:char array

Introduction

Function Tests for
islower() Lowercase letter
isupper() Uppercase letter
isalpha() Uppercase or lowercase letter
isalnum() Uppercase or lowercase letter or a digit
iscntrl() Control character
isprint() Any printing character including space
isgraph() Any printing character except space
isdigit() Decimal digit ( '0' to '9')
isxdigit() Hexadecimal digit ( '0' to '9', 'A' to 'F', 'a' to 'f')
isblank() Standard blank characters (space, '\t')
isspace() Whitespace character (space, '\n', '\t', '\v', '\r', '\f')
ispunct() Printing character for which isspace() and isalnum() return false

Demo Code

#include <stdio.h>
#include <ctype.h>
#define BUF_SIZE 100//from   www . j  a  va 2  s .com

int main(void)
{
  char buf[BUF_SIZE];              // Input buffer
  int nLetters = 0;                // Number of letters in input
  int nDigits = 0;                 // Number of digits in input
  int nPunct = 0;                  // Number of punctuation characters

  printf("Enter an interesting string of less than %d characters:\n", BUF_SIZE);
  if(!gets_s(buf, sizeof(buf)))    // Read a string into buffer
  {
    printf("Error reading string.\n");
    return 1;
  }
  size_t i = 0;                    // Buffer index
  while(buf[i])
  {
    if(isalpha(buf[i]))
      ++nLetters;                  // Increment letter count
    else if(isdigit(buf[i]))
      ++nDigits;                   // Increment digit count
    else if(ispunct(buf[i]))
      ++nPunct;
    ++i;
  }
  printf("\nYour string contained %d letters, %d digits and %d punctuation characters.\n",
                                              nLetters, nDigits, nPunct);
  return 0;
}

Result


Related Tutorials