Topic 18 Characters and Strings 1
Characters In C/C++, character constants are written surrounded by single quotes e.g . 'a' or '?' or '4' . A variable of type char can be used to store a single character. char ch; ch = 'a'; When we want to store many characters, we can use an array of characters. 2
Array of Characters Example: array to store 5 characters. char letters; letters = 'a'; letters = 'p'; letters = 'p'; letters = 'l'; letters = 'e'; for(int i = 0; i < 5; i++) cout << letters[i]; 3
Character Manipulation Functions C++ provides a set of functions for manipulating characters. To use these functions in your program, remember to add this #include directive in your program: #include <cctype> 4
Character Manipulation Functions These functions are divided into 2 groups: classifying functions and converting functions Classifying functions examine a character and tell if it belongs to a given classification. These functions names all start with ‘is’ and return true or false. 5
Character Manipulation Functions Function Description isalpha Checks if the character is an alphabetic character (a-z or A-Z) isdigit Checks if the character is a digit (0-9) isalnum Checks if the character is an alphabetic (a-z or A-Z) or numeric (0- 9) character Ispunct Check if character is a punctuation character (',', '!', '?', etc) 6
Character Manipulation Functions Function Description isupper Checks if the character is an uppercase alphabetic character (A-Z) islower Checks if the character is a lowercase alphabetic character (a-z) isspace Checks if the character is a whitespace ( blank space (' '), horizontal tab ('\t'), line feed ('\n'), vertical tab ('\v'), form feed ('\f'), or carriage return ('\r') ) 7
Character Manipulation Functions Character conversion functions convert a character from one case to another. Function Description toupper Converts lowercase to uppercase. If not lowercase, returns it unchanged. tolower Converts uppercase to lowercase. If not uppercase, returns it unchanged. 8
Character Function Examples Example: To input a character and check if it is an alphabet or digit. char ch; cout << "Enter a character: "; cin >> ch; if( isalpha(ch) ) cout << "It is an alphabet"; else if( isdigit(ch) ) cout << "It is a digit"; else cout << "Not alphabet or digit"; 9
Character Function Examples Example: To convert all the characters in an array to uppercase. char letters; letters = 'a'; letters = 'p'; letters = 'p'; letters = 'l'; letters = 'e'; for(int i = 0; i < 5; i++) letters[i] = toupper(letters[i]) ; 10
Characters and ASCII Codes Remember that a character is represented in the computer using ASCII code. We can display the character using either the character or its ASCII code in object cin.
You've reached the end of your free preview.
Want to read all 49 pages?
- Summer '16
- Sue Chye