Chapter 8 C Characters and Strings
Objectives of This Chapter To use the functions of the character handling library (<ctype.h>). To use the string conversion functions of the general utilities library (<stdlib.h>). To use the string and character input/output functions of the standard input/output library (<stdio.h>). To use the string processing functions of the string handling library (<string.h>). The power of function libraries for achieving software reusability.
Page 342 CHARACTERS: Characters are the fundamental building blocks of source programs. Every program is composed of a sequence of characters that when grouped together meaningfully is interpreted by the computer as a series of instructions used to accomplish a task. Computers are designed to work with numbers, so computers deal with the characters in terms of character constants. A character constant is an int value represented as a character in single quotes. The value of a character constant is the integer value of the character in the machine s character set commonly referred as ASCII table. ASCII stands for American Standard Code for Information Interchange. In C, a character is expressed in single quotation marks. ( char a=`y`). For example: 'z' represents the integer value of z, and '\n' the integer value of newline are 122 and 10 in ASCII, respectively.
ASCII TABLE : Character Constants in Machine Language are listed below referred as ASCII TABLE. \0 is NULL character. \33 is! character. \65 is A character. The Ascii Table is worldwide accepted and standard for the all computer systems. Most of character manipulation operations are done based on this table.
ASCII CHARACTER TABLE : Conversion Programs Programs to convert a character to ASCII number and ASCII number to character.** * Output of the Program * * Output of the Program *
More on ASCII TABLE Character Constants As one may notice from Table: Characters are grouped in meaningful ordered.*** For instance; 47 < Digits < 58 64 < Alphabetic Upper Case < 91 96 < Alphabetic Lower Case < 123 By considering that the digits, letters, fall into a range. One may classify/manipulate the characters based on their ASCII number.* Example: Program that converts a Character from Lower Case to Upper Case char c=`o`; // Note that ASCII number for `o` is 111. if ( c > 96 && c < 123){ // Note that 96 < Alphabetic Lower Case < 123 c =32; // This assign the ASCII number 111 32 = 79 printf( %c,c); // This will print This kind of functions are available under C libraries we will learn how to use them
Page 342 STRINGS: Strings are collection of characters. Strings may include letters (a, Z, c, etc.), digits (0,8,7, etc.), or various special characters (:,., *, +, &, etc). In C, strings are written in double quotation marks. In C programming, we treat strings as characters arrays. Always last element of a string is a null character ( \0 ). In C, we may also deal with strings using string pointers ( char * ). Initialization of a string array can be done in different ways; char color[] = "blue"; // initializing by a string (double quotation marks). char *colorptr = "blue"; // initializing string pointer char color[] = { 'b', 'l', 'u', 'e', '\0' }; // initializing by characters (single quotation marks). scanf ( %s,color); // reading from keyboard (first element = mem. Add.)
Page 344 In some programs, we may need to identify or manipulate characters or strings. There are various libraries including function to deal with characters. The character handling library (ctype.h) presents several function to test/classify (test what type of character) and modify a character data. Test/Classification Functions: isdigit, isalpha, isalnum, isxdigit, islower, isupper, isspace, iscntrl, etc. The test functions receives a character (constant character) as argument. Returns: TRUE (1 or non zero in logic) if the result of test is true. FALSE (0 in logic) if the result of the test is false. Manipulation/Conversion Functions: toupper and tolower. Manipulation functions also receives character as argument (as constant character) then returns the value after conversion.
Complete list of character handling library (ctype.h) functions: Page 344
CONDITIONAL OPERATOR :? : Condition? Exp1 : Exp2 Similar to usage of single if else statement one may also use conditional operator? : to do the same task. If ( condition ) {Expression 1} else {Expression 2 } condition? Expression 1 : Expression 2 ; Means Do Expression 1 if TRUE otherwise Do Expression 2 Example: Showing some of the usage of conditional expressions printf("%d",x > y? x : y ); // print the value of x if bigger, otherwise print y z = x > y? x : y; // assing the value of x to z if bigger, otherwise assign y x > y? x++ : y++; //increase x by 1 if bigger otherwise increase y by 1
Example: Usage of CONDITIONAL OPERATOR :? : What will be the output of the following program?* * Output of the Program *
Example: Functions isdigit, isalpha, isalnum, and isxdigit Page 345 Following program demonstrates the usage of functions* * Output of the Program *
Example: Functions islower, isupper, tolower, and toupperpage 345 Following program demonstrates the usage of functions* * Output of the Program *
Example: Functions isspace, iscntrl, ispunct, isprint and isgraph Page 347 Following program demonstrates the usage of functions* * Output of the Program *
STRING MANUPILATION LIBRARIES Character Handling Library functions can be used only for characters (single character variables). As we know, the Strings are collection of characters. Strings may include letters (a, Z, c, etc.), digits (0,8,7, etc.), or various special characters (:,., *, +, &, etc). There are also other functions in C libraries; these functions enable the programmers to manipulate the strings (set of characters character arrays instead of only one character), which useful in most programs. Most of library functions associate with string operations will be presented in this chapter.
Page 349 This section presents the string conversion functions from the general utilities library (<stdlib.h>). This libraries can be used to convert a string of digits to double, integer, long integer, unsigned long integer. Why we should ever need to store numbers in a string? Remember: 999 Main Street or consider processing a complete line.
Function atof ( a string to a double) Page 350 atof function converts its argument (input) to a double number. Inputted string should consist of digits with floating point representing a meaningful double number, otherwise the behavior of atof function will be undefined. * * Output of the Program *
Function atoi ( a string to an integer) Page 350 atoi function converts its argument (input) to an integer number. Inputted string should consist of digits representing a meaningful integer number, otherwise the behavior of atoi function will be undefined. * * Output of the Program *
Function atol ( a string to a long int.) Page 351 atol function converts its argument (input) to a long integer number. Inputted string should consist of digits representing a meaningful long integer number, otherwise the behavior of atol function will be undefined. * * Output of the Program *
Function strtod ( seq. of char. to a double) Page 351 Similar to atod, strtod function also used to convert a string to a double number. But strtod is capable of processing a sequence of characters (string) partially including a double number. It accepts two arguments, first arguments is the string to be converted and second one is a character pointer that will be pointed by strtod to the remainder of string after conversion.* * Output of the Program *
Function strtol ( seq. of char. to a long integer ) Page 352 Similar to atol, strtol function also used to convert a string to a long integer number. But strtol is capable of processing a sequence of characters (string) partially including a meaningful long integer. It accepts three arguments, first arguments is the string to be converted, second one is a character pointer that will be pointed by strtol to the character positioned after the long integer, and third argument is the base (0 36) of number system. (Decimal:0 or10, Octal (8), Binary (2), Hex (16)) * * Output of the Program *
Function strtoul ( seq. of char. to a unsigned long integer) Page 353 strtoul function can be used to convert a string partially including an unsigned long integer number to an unsigned long integer number. It works pretty much similar to strtol function in terms of arguments (string, remainder, and base). * Output of the Program *
Page 354 This section presents several functions from the standard input/output library (<stdio.h>). These functions specifically can be used to input and manipulate string variables. Below table summaries arguments and return values of these functions.
Function fgets and putchar Explanation Page 355 Example: stream stdin is used to imply the keyboard can be also used as file. char sentence[ 80 ]; /* create char array */ fgets( sentence, 80, stdin ); /* using fgets to read line of text until \n newline*/ Example: Using putchar to print a single character to screen char str[ ] = Welcome to computer World! ; /* create char array */ int i=0; while ( ++i!= `\0`) putchar ( str[i]); /* using putchar to printing the string*/ another example; putchar (! ); /* using putchar to print single character! */
Function fgets and putchar Example Program Page 356 * Output of the Program *
Function getchar and puts Explanation Page 355 Example: getchar can be used to read a single character from keyboard. char a; /* define a single character variable */ a=getchar() /* using getchar to read a single char from keyboard it is load to a*/ putchar(a); /* using putchar to print the char variable */ getchar alternatives are getch() and getche() another example; char string[ 80 ] ; /* create char array */ int i=0; while ( ( string[i] = getch() )!= \n ) { i++ ; } /* Inputting whole line into string character */ Example: puts prints a string to a the screen followed by new line character char str[ ] = Welcome to computer World! ; /* create char array */ puts( str ); /* printing the string same as printf( %s\n,str); */ another example; puts( Welcome ); /* printing the string same as printf( %s\n, Welcome ); */
Function getchar and puts Example Program Page 356 * Output of the Program *
Function sprintf Explanation Page 357 sprintf works same as printf but it writes into a string instead of the screen. Example: sprintf can be used to write variable/s into a string array. char str[ 80 ] ; /* create char array */ int x = 100; double y = 3.4; printf( %5d%5.2d, x, y); /* print the variables to screen*/ sprintf( str, %5d%5.2d, x, y); /* print the variables to str string*/
Function sprintf Example Page 357 * Output of the Program *
Function sscanf Explanation Page 357 sscanf works same as scanf but it reads from a string instead of the screen. Example: sscanf can be used to read variable/s from a string array. char str[ 80 ] = 112 Ahmet ; /* create char array */ char name[30]; int x; scanf( %d%s, &x, name); /* reading the variables from keyboard*/ sscanf( str, %d%s, &x, name); /* reading the variables from the str string */
Function sscanf Example Page 358 * Output of the Program *
Page 358 The string handling library (<string.h>) provides many useful functions to manipulate string data. In this section, we will learn these functions in detail. (Copying Concatenating Separating Length of a String) Below table summaries arguments and return values of these functions.
Function strcpy and strncpy Explanation Page 359 Example: strcpy ( s1, s2 ) copies s2 string to s1 string. char str1[10], str2[]= Welcome ; /* defining two strings */ strcpy ( str1, str2 ); /* Copying str2 into str1 */ another example; char str[ 40 ] ; /* create char array */ strcpy ( str, Gaziantep / Sahinbey ); Example: strncpy ( s1, s2, n ) Copies n byte of data (1 character = 1 Byte) from s2 to s1. char str1[10], str2[]= Welcome ; /* defining two strings */ strncpy ( str1, str2, 3); /* Copying 3 character from str2 into str1 */ Note: If the n is less then the size of the str2, it doesn t \0 character.
Function strcpy and strncpy Example Program Page 359 * Output of the Program *
Function strcat and strncat Explanation Page 360 Example: strcat ( s1, s2 ) Append/Add s2 string to s1 string It starts appending from the `\0` of the s1. char str1[30]= James, str2[]= Polansky ; /* defining two strings */ strcat ( str1, str2 ); /* Appends str2 into str1 */ str2 becomes James Polansky Example: strncat ( s1, s2, n ) Appends n character from s2 to s1. char str1[30]= James, str2[]= Polansky ; /* defining two strings */ strncat ( str1, str2, 3); /* Appending 3 characters from str2 to str1 */ Note: If the n is less then the size of the str2, it doesn t append \0 character.
Function strcat and strncat Example Program Page 360 * Output of the Program *
Page 361 The string handling library (<string.h>) also provides function those can be used to compare two strings character by character. Below table summaries usage and the brief description these functions.
Function strcmp and strncmp Explanation Page 361 Example: strcmp ( s1, s2 ) compares s2 string to s1 string. char str1[]= Ali, str2[]= Ahmet ; /* defining two strings */ int result; result = strcmp ( str1, str2 ); /* Comparing str2 into str1 */ if str1 and str2 are same then result is 0. if str1 is greater than str2 are same then result is > 0. if str1 is less than str2 are same then result is < 0. strncmp ( s1, s2, n ) same as strcmp but compares only n characters. Note: Greater and Less means the alphabetical ordering or the strings. The function uses the ASCII codes of each characters. This functions can be used to order strings alphebetically.
Function strcmp and strncmp Example Program Page 361 * Output of the Program *
Page 363 The string handling library (<string.h>) also provides function those can be used to search characters or strings in another string. Below table summaries usage and the brief description these functions. Here; We will only present strchr, strstr, and strtok functions. You should review examples for the other functions and learn by your own.
Function strchr Explanation Page 364 Example: strchr ( s, c ) If character not included in string returns NULL char str[]= Gaziantep ; /* defining two strings */ char c = n ; /* defining a character variable */ if ( strchr ( str, c )! = NULL ) printf( %c is found in %s, c, str ); else printf( %c is not found in %s, c, str ); Because n exist in Gaziantep, it will print to screen n is found in Gaziantep
Function strchr Example Program Page 364 * Output of the Program *
Function strstr Explanation Page 367 strstr can be used to search a string in another string. It s return value is a pointer. If the s2 is found in s1 then the returned pointer points the first occurrence of s2 in s1. If it is not found then it returns a NULL pointer. Example: strstr ( s1, s2 ) If s2 is not included in s1 returns NULL char str1[]= Gaziantep ; /* defining two strings */ char str2[]= az ; /* defining a character variable */ if ( strstr ( str1, str2 )! = NULL ) {printf( %s is found in %s, str2, str1 ); printf( \nreturn Value: %s is found in %s, strstr(str2, str1) ); } else printf( %s is not found in %s, str2, str1 );
Function strstr Example Program Page 367 * Output of the Program *
Function strtok Explanation Page 368 strtok can be used to tokenize a string into small pieces like words. A token here means the sequence of characters separated by a specific character (delimiters) like space or dash ( ). Example: strtok ( s, c ) If c delimiter found string, it returns the first sequence of the characters found in c. If no more specified character found in s, it returns NULL. char str[]= I live in Gaziantep. ; /* defining a strings */ char *ptr; /* define a character pointer */ ptr = strtok (str, ); /* tokenizing sting ptr becomes I */ if ( ptr! = NULL ) printf ( %s\n, ptr); /* prints I */ ptr = strtok (NULL, ); /* tokenize again ptr becomes live */ if ( ptr! = NULL ) printf ( %s\n, ptr); /* prints live */ This idea can be used to break up a sentence in to words.
Function strtok Example Program Page 368 * Output of the Program *
Page 369 There are memory functions in C libraries (stdlib.h) that allows programmers to manipulate, compare, and search block of data in the memory. These functions can be used to manipulate, compare, and search string by treating the block of data as a string (objects string arrays). Below table summaries usage and the brief description these functions. Notice that; The pointer parameters (arguments) are defined as void * so they can be used to manipulate any type of data.
Function memcpy Explanation Page 370 memcpy can be used to copy a specified number of characters from the second argument to first argument. This does copy the `\0` if it is within the range otherwise only copies and overwrites the indicated n characters. Example: memcpy ( s1, s2, n ) copy n character from s2 to s1. char str1[]= Gaziantep ; /* defining two strings */ char str2[]= 123_A ; /* defining a character variable */ printf( Before str1:%s, str1 ); /* prints Gaziantep */ memcpy ( str1, str2,5); printf( After str1:%s, str1 ); /* prints 123_Antep */
Function memcpy Example Program Page 370 * Output of the Program *
Function memmove Explanation Page 371 memmove can be used to copy a specified number of characters from the second argument to first argument similar to memcpy. But this memmove can be used to move the data within the same object. Example: memmove ( s1, s2, n ) copy n character from s2 object to s1. char str[]= Call Sweet Home ; /* defining two strings */ printf( Before str:%s, str ); /* Call Sweet Home */ memmove ( str, &str[11],5); /* Copy 5 character from 11 th element */ printf( After str:%s, str ); /* Home Sweet Home */
Function memmove Example Program Page 371 memmove ( x, &x[5], 10 ) First arguments x points the x[0] Second argument points the 5 th element ( x[5] is S). Starting from S, it copies 10 element on to the first pointer ( x[0]). * Output of the Program *
Function memcmp Explanation Page 371 memcmp can be used to compare a specified number of characters from the second argument with specified number of characters from first argument similar to strcmp. If s1 and s2 are the same then returns 0 If s1 is greater than the s2 then returns 1 If s1 is less than the s2 then returns 1 Example: memcmp ( s1, s2, n ) Compares n characters in s1 and s2 objects. char str1[]= ABC123, str2[]= ABc123 ; /* defining two strings */ printf( Comparing only 2 characters:%d, memcmp(str1, str2, 2 ); /* 0 */ printf( Comparing only 3 characters:%d, memcmp(str1, str2, 3 ); /* 1 */ printf( Comparing only 3 characters:%d, memcmp(str2, str1, 3 ); /* 1 */
Function memcmp Example Program Page 371 memcmp ( str1, str2, n ) compares the strings alphabetically for n Characters. 0 : str1 and str2 same for n character. 1 : str1 greater than str2 means it should come after str2 alphabetically. 1 : str1 less than str2 means it should come before str2 alphabetically. * Output of the Program *
Function memchr Explanation Page 372 memchr can be used to search for a character in a string. If character c is found then a pointer to first occurrence of the character is returned. If not found then NULL character is returned. Example: memchr ( s, c, n ) Searches n characters in s for c. char str1[]= ABC123, str2[]= ABc123 ; /* defining two strings */ printf( Searching for C:%s, memchr(str1, C, 6 ); /* prints C123 */ printf( Searching for C:%s, memchr(str2, C, 6 ); /* prints null */ printf( Searching for C:%s, memchr(str2, c, 6 ); /* prints c123 */ printf( Searching for C:%s, memchr(str2, c, 2 ); /* prints NULL */ printf( Searching for C:%s, memchr(str2, c, 3 ); /* prints c123 */
Function memchr Example Program Page 372 memchr ( s, `r`, 16 ) searches for r in 16 character of s array. Found, so returning pointer will be pointing the `r` in the array. * Output of the Program *
Function memset Explanation Page 372 memset can be used to assign/copy/write a character value to specified number of elements in a string array. Example: memset ( s, c, n ) Assign c to n characters in s. char str[]= ABC123 ; /* defining two strings */ memset (str, q, 3); /* it writes q to first three elements > qqq123*/
Function memset Example Program Page 372 memset ( s, `b`, 7 ) inserts/assign `b` character to 7 elements in s. Note: Return values is also the string1 after assigning the requested character. * Output of the Program *
Page 373 The two remaining functions of this chapter are the sterror and strlen. While running a program, some errors may take place/occur. In order track down the errors in a program. Error codes can be tracked down using errno.h library. Then strerror function can be used to print these error codes in a user friendly format. strlen function determines the length of a string. \0 is not included in the calculated length.
Function strerr Example Program Page 373 * Output of the Program *
Function strlen Example Program Page 372 strlen ( string1 ) returns the length of the string excluding `\0`. * Output of the Program *
Page 370 * Some Outputs of the Program * YOU MAY ALSO USE MEMCMP INSTEAD OF STRCMP
Page 372 * Output of the Program *
Page 371 * Output of the Program *
Page 371 * Output of the Program *
Page 371 * Output of the Program *
Page 374 * Some Outputs of the Program *