C - Strings Character Analyzing and Transforming

Introduction

You can examine the characters in a string using the functions in the ctype.h header.

The following table shows the functions that will test for various categories of characters.

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

The argument to these function is the character to be tested.

All these functions return a nonzero value of type int if the character is within the set that's being tested for; otherwise, they return 0.

The following example determines how many digits, letters, and punctuation characters there are in a string that's entered from the keyboard:

Demo

#define __STDC_WANT_LIB_EXT1__ 1   // Make optional versions of functions available
#include <stdio.h>
#include <ctype.h>
#define BUF_SIZE 100//from   w w  w  . j  a v  a2 s  . c o  m

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

how It Works

You read the string into the array, buf, within the following if statement:

if(!gets_s(buf, sizeof(buf)))  // Read a string into buffer
{
      printf("Error reading string.\n");
      return 1;
}

the statements that analyze the string are as follows:

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;
}