C Tutorial (19) : C built-in functions for strings

C includes many helpful built-in functions in addition to ones such as strlen(), getchar(), and printf(). This tutorial explains the most common and helpful character and string functions.

Character-Testing Functions

C has several built-in character-testing functions. The character-testing functions can help you determine exactly what kind of input characters your program receives. You can set up if logic to execute certain courses of action based on the results of the character tests.

Note : You must include the ctype.h header file at the top of any program that uses the character functions described in this tutorial.

The isalpha() function returns true (which is 1 to C) if the value in its parentheses is an alphabetic character a through z (or the uppercase A through Z) and returns false (which is 0 to C) if the value in parentheses is any other character. Consider this if:

if (isalpha(inChar))
  printf("Your input was a letter.\n");

The message prints only if inChar contains an alphabetic letter.

C has a corresponding function named isdigit() that returns true if the character in the parentheses is a number from 0 through 9. The following if prints A number if inChar contains a digit:

if (isdigit(inChar))
  printf("A number\n");

Note : Both isalpha() and isdigit() test character content and return the relational result of the test.

Case Testing

The isupper() and islower() functions let you know whether a variable contains an upper- or lowercase value. Using isupper() keeps you from having to write long if statements like this:

if ((inLetter >= 'A') && (inLetter <= 'Z'))
  printf("Letter is uppercase\n");

Instead, use isupper() in place of the logical comparison:

if (isupper(inLetter))
  printf("Letter is uppercase\n");

Note :  islower() tests for lowercase values in the same way as isupper() tests for uppercase values.

/* This program asks a user for a username and a password.
   It tests whether their password has an uppercase letter,
   lowercase letter, and a digit. If it does,
   the program congratulates their selection. If not,
   it suggests they might want to consider a password with more
   variety for the sake of security. */

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

int i;
int hasUpper, hasLower, hasDigit; 
char user[25], password[25];

//Initialize all three test variables to 0 i.e. false 

hasUpper = hasLower = hasDigit = 0;
printf("What is your username? "); 
scanf(" %s", user);

printf("Please create a password: "); 
scanf(" %s", password);

//This loop goes through each character of the password and tests
  whether it is a digit, upppercase letter, then lowercase

for (i = 0; i < strlen(password) ; i++ )
if (isdigit(password[i]))
  hasDigit = 1; continue;
if (isupper(password[i]))
  hasUpper = 1; continue;

if (islower(password[i]))
  hasLower = 1;

/* The if portion will only execute if all three variables below are 1,
   and the variables will only equal 1 if the appropriate characters were
   each found */

if ((hasDigit) && (hasUpper) && (hasLower))
  printf("\n\nExcellent work, %s,\n", user); 
  printf("Your password has upper and lowercase "); 
  printf("letters and a number.");
  printf("\n\nYou should consider a new password, %s,\n", user);
  printf("One that uses upper and lowercase letters "); 
  printf("and a number.");

Tip : Some passwords today also ask for at least one non-letter, non-number character (such as $, !, *, &, and so on). You could further refine this code to check for those by putting an else at the end of the final islower test. After all, if a character fails the first three tests, then it fits in this last category.

Case-Changing Functions

C has two important character-changing functions (also called character-mapping functions) that return their arguments changed a bit. Unlike isupper() and islower(), which only test character values and return a true or false result of the test, toupper() and tolower() return their arguments converted to a different case. toupper() returns its parentheses argument as uppercase. tolower() returns its parentheses argument as lowercase.

The following program segment prints yes or no, depending on the user’s input. Without the toupper() function, you need an extra test to execute your plan:

if ((userInput == 'Y') || (userInput == 'y'))

The next set of statements uses the toupper() function to streamline the if statement’s logical test for lowercase letters:

if (toupper(userInput) == 'Y') // only need to test for upper case 


String Functions

The string.h header file contains descriptions for more functions than just strcpy() and strlen(). This section explains the strcat() function that lets you merge two character arrays, as long as the arrays hold strings. strcat() stands for string concatenation.

strcat() takes one string and appends it to—that is, adds it onto the end of—another string. This code fragment shows what happens with strcat():

char first[25] = "Anukul"; 
char last[25] = " Verma";

strcat(first, last); //Adds last to the end of first 
printf("I am %s\n", first);

Here is the output of this code:
I am Anukul Verma

strcat() requires two string arguments. strcat() tacks the second string onto the end of the first one. The space appears before the last name only because the last array is initialized with a space before the last name in the second line.

Warning : You are responsible for making sure that the first array is large enough to hold both strings. If you attempt to concatenate a second string to the end of another string, and the second string is not defined with enough characters to hold the two strings, strange and unpredictable results can happen.

Because the second argument for strcat() is not changed, you can use a string literal in place of a character array for the second argument, if you like.

The puts() and gets() functions provide an easy way to print and get strings. Their descriptions are in stdio.h, so you don’t have to add another header file for puts() and gets(). puts() sends a string to the screen, and gets() gets a string from the keyboard. The following program demonstrates gets() and puts(). As you look through it, notice that neither printf() nor scanf() is required to input and print strings.

/* This program asks a user for their hometown and 
   the two-letter abbreviation of their home state. 
   It then uses string concatenation to build a new string 
   with both town and state and prints it using puts. */

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

 char city[15];
 // 2 chars for the state abbrev. and one for the null zero 
 char st[3];
 char fullLocation[18] = "";

  puts("What town do you live in? "); 

  puts("What state do you live in? (2-letter abbreviation)"); 

  /* Concatenates the strings */ 
  strcat(fullLocation, city);

  strcat(fullLocation, ", "); //Adds a comma and space between the city

  strcat(fullLocation, st); //and the state abbreviation

  puts("\nYou live in "); 

Here is the output from a sample run of this program:

What town do you live in?
XYZ City
What state do you live in? (2-letter abbreviation)
You live in
XYZ City, IN

puts() automatically puts a newline at the end of every string it prints. You don’t have to add a \n at the end of an output string unless you want an extra blank line printed.

Note : gets() converts the Enter keypress to a null zero to ensure that the data obtained from the keyboard winds up being a null-terminated string instead of an array of single characters.

One of the most important reasons to use gets() over scanf() is that you can ask the user for strings that contain embedded spaces, such as a full name (first and last name). scanf() cannot accept strings with spaces; scanf() stops getting user input at the first space.

getch, putch, getchar & putchar < Prev                  Next > functions for MATH



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s