Topic 20 Characters and Strings
Topic 20
Characters and Strings
Characters
In 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.
Array of Characters
Example: array to store 5 characters.
char letters[5]; int i; letters[0] = 'a'; letters[1] = 'p'; letters[2] = 'p'; letters[3] = 'l'; letters[4] = 'e'; for (i=0; i<5; i++) printf("%c", letters[i]);
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 <ctype.h>
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.
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
isupper Checks if the character is an
uppercase alphabetic character (A-Z)
Character Manipulation Functions
Function Description
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’))
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.
Character Function Examples
Example: To input a character and check if it is an
alphabet or digit.
char ch; printf("Enter a character: "); scanf("%c", &ch); if (isalpha(ch)) printf("It is an alphabet"); else if (isdigit(ch)) printf("It is a digit"); else printf("Not alphabet or digit");
Character Function Examples
Example: To convert all the characters in an array
to uppercase.
char ch[10]; int i; for (i=0; i<10; i++) ch[i] = toupper(ch[i]);
Characters and ASCII Codes
Remember that a character is represented in the
computer using ASCII code.
We can display the character using either %c (to
display the character) or %d (to display its ASCII
code) in function printf.
Example:
char ch; ch = 'a'; printf("Character is %c\n", ch); printf("Its ASCII code is %d\n", ch);
Displays
letter ‘a’ Displays
ASCII code
for ‘a’ i.e.
97
Characters and ASCII Codes
We can perform operations using the ASCII code.
Example: Given a character, generate the next
character in the alphabet.
char chIn, chOut; printf("Enter a character: "); scanf("%c", &chIn); if (isalpha(chIn)) // check if alphabetic { // character chOut = chIn + 1; printf("The next character is %c\n", ch); }
Note: Does not work if input character is z or Z
Strings
In C, string constants are written surrounded by
double quotes e.g. "Sales" or "Total\n".
Note: There is no type string in C.
But C allows us to use an array of characters to
store a string.
C also provides many functions to perform string
manipulation.
Strings
C treats a string differently from a normal array of
characters.
C uses a delimiter to indicate the end of the string.
The delimiter is a special character called a null
character.
Strings
The null character is represented by the character
sequence ‘\0’.
So a string is stored in C as an array of characters
but with a delimiter (‘\0’) to indicate the end of the
string.
Strings versus Array of Characters
An array of
A string characters
Strings
A string constant with one character is different
from a character constant.
An empty string is ""(two double quotes
without any space in between).
""
Strings
When we want to store a string, we declare an
array of characters.
The size of the array must be large enough to
store all the characters we want plus the null
character.
So the size is the maximum length of the string
plus one.
Example – to store a string with a maximum of 8
characters:
char str[9];
Initializing Strings
We can initialize a string variable using the index.
Example:
char str[9];
str[0] = ‘b’;
str[1] = ‘y’;
str[2] = ‘e’;
str[3] = ‘\0’;
b e y \0 ? ? ? ? ?
0 1 2 3 4 5 6 7 8
Part of array but
not part of string
Initializing Strings
We can also define and initialize it using a string
constant.
Example:
char str[9] = “bye”;
Note: the null character is added automatically.
b e y \0 ? ? ? ? ?
0 1 2 3 4 5 6 7 8
Using Function scanf for Strings
The function scanf can be used to input strings.
The conversion specification code for a string is s.
Example:
char str[9];
scanf("%s", str); // read a string
Note: the address operator (&) is not needed because the array name itself is a pointer type and therefore has the address of the first element of the array.
Using Function scanf for Strings
Function scanf adds the null character ‘\0’ at the
end of the string.
The maximum number of characters entered must
be one less than the size of the array.
If the number of characters entered is less than
the maximum number allowed, the remaining
spaces are undefined.
Using Function scanf for Strings
Example:
char str[9];
scanf("%s", str); // read a string
Suppose the user entered characters: good
The array str will contain:
g o o d \0 ? ? ? ?
0 1 2 3 4 5 6 7 8
Using Function scanf for Strings
Function scanf skips whitespace (blanks,
newlines, tabs) until it finds a character.
Then it reads the characters and stores them in
the array until it finds a whitespace.
Example Input Values What is stored in str
abc abc\0
12345678 12345678\0
abc def abc\0
abcd abcd\0
1234567890 Invalid input - error
Using Function scanf for Strings
To ensure that the user does not enter more than
the maximum number of characters allowed, we
can specify the maximum using the width
specification.
Example:
scanf("%8s", str); // read a string with a
// maximum of 8 characters
Example Input
Values
What is stored in str
abc abc\0
1234567890 12345678\0
Using Function printf for Strings
The function printf can be used to display strings.
The conversion specification code for a string is s.
The width can be used together with the
justification flag.
Examples: if str contains: good
Examples Output
printf("|%s|", str); |good|
printf("|%10s|", str); | good|
printf("|%-10s|", str); |good |
Using Function printf for Strings
Note: we use the array name in the printf function
call. This passes the address of the first element
to the printf function.
We can also write this:
printf("|%s|", &str[0] );
Using Function printf for Strings
We can also display part of the string.
Examples: if str contains: good
The function displays the characters starting from
the specified position until the end of the string.
Examples Output
printf(“%s", &str[0] ); good
printf(“%s", &str[1] ); ood
printf(“%s", &str[2] ); od
String Input with Spaces
The function scanf cannot be used to read a string that contains spaces.
We use the function gets instead.
Example:
char str[50];
gets(str);
The function reads characters (including spaces) until the end of line (user presses <enter> key which generates a newline) or end-of-file (user presses control-z ).
String Input with Spaces
If a newline character is read, function gets
discards the character and replaces it with a null
character.
Example:
String Manipulation Functions
C provides a set of functions for string
manipulation.
These function names start with ‘str’.
To use these functions in your program,
remember to add this #include directive in your
program:
#include <string.h>
String Functions – strlen
The function strlen returns the length of a string i..e the number of characters in the string excluding the null character.
If the string is empty, it returns 0.
Example: char str1[8] = “abc”;
strlen( str1 ) – returns 3
char str2[8] = “”; // empty string
strlen( str2 ) – returns 0
char str3[8] = “ ”; // one space
strlen( str3 ) – returns 1
String Functions – strlen
Note that we pass the whole array (representing
the string) to the function strlen.
This means the we are passing the address of the
first element.
So the function can also be called as:
strlen( &str[0] )
String Functions – strcpy
The function strcpy copies the contents of one
string to another.
Example: strcpy( s1, s2 )
String Functions – strcpy
We can also copy part of the word.
Example: strcpy( s1, &s2[5] )
String Functions – strncpy
The function strncpy is similar to function strcpy.
The difference is that we can specify the number
of characters to copy.
If the length of the string that is copied is less than
the number specified, the remaining places are
filled with the null character (‘\0’).
String Functions – strncpy
Example: strncpy( s1, s2, 8)
String Functions – strcmp
The function strcmp compares two strings to
determine if they are equal.
Example: strcmp( s1, s2 )
The strings are compared character by character
until unequal characters are found or until the end
of the strings is reached.
The function returns an integer to indicate the
results of the compare.
String Functions – strcmp
1) If the two strings are equal, the function returns
0.
String Functions – strcmp
2) If the first string is less than the second string,
the function returns a value less than 0 (i.e. a
negative value).
String Functions – strcmp
3) If the first string is greater than the second
string, the function returns a value greater than 0
(i.e. a positive value).
String Functions – strcmp
Example:
if (strcmp( s1, s2 ) == 0)
// strings are equal
else
// strings are not equal
if (strcmp( s1, s2 ) < 0)
//string s1 is less than string s2
if (strcmp( s1, s2 ) > 0)
// string s1 is greater than s2
String Functions – strcat
The function strcat appends or concatenates one
string to the end of another string.
Example: strcat( s1, s2 )
Note: The size of the destination string must be
large enough to hold the resulting string.
String Functions – strncat
The function strncat is similar to the function
strcat,
The difference is that we can specify the number
of characters to concatenate.
Example: strncat( s1, s2, 3 )
String Examples
Example: To input a word and display each
character of the word on a separate line.
char word[10]; int len, i; printf("Enter a word: "); scanf("%s", word); len = strlen(word); printf("The letters are:\n"); for (i=0; i<len; i++) printf("%c\n", word[i]);
String Examples
Example: To input a line of text and count the
number of spaces.
char line[80]; int spaces, len, i; printf("Enter a line of text:\n"); gets(line); spaces = 0; len = strlen(line); for (i=0; i<len; i++) if (line[i] == ' ') spaces++;
String Examples
Example: To input a word and display the word in
parts
Assume user enters: abc
char word[20]; int len, i; printf("Enter a word: "); scanf("%s", word); for (i=0; i<len; i++) printf("%s\n", &word[i]);
i &word[i] output
0 &word[0] abc
1 &word[1] bc
2 &word[2] c
Case Study 1
Problem:
Write a program that accepts a word from the
user and displays the word in pig-latin.
To form a word in pig-latin, the first letter of the
word is removed and added at the end of the
word and the letters ay are added after the added
letter.
However, if the word starts with a vowel (‘a’, ‘e’, ‘i’,
‘o’, or ‘u’), simply append the letters ay.
Case Study 1
Design the solution:
First we need to get the first letter of the word.
Next we copy the remaining letters to the new pig-
latin word.
If the first letter is not ‘a’, ‘e’, ‘i’, ‘o’ or ‘u’, we
append the first letter at the end of the new pig-
latin word.
Finally we append the letters “ay” to the end of the
new pig-latin word.
Case Study 1 – Complete Program #include <stdio.h> void pig_latin(char word[], char pigLatinWord[]); int main(void) { char inputWord[21]; // maximum 20-letter word char outputWord[23]; // need space for ay printf("Enter a word: "); scanf("%s", inputWord); pig_latin(inputWord, outputWord); printf("The word in pig latin is %s\n", outputWord); return 0 }
Case Study 1 – Complete Program
void pig_latin(char word[], char pigLatinWord[]); { char firstLetter; int len; firstLetter = word[0]; strcpy( pigLatinWord, &word[1] );
Case Study 1 – Complete Program
if (firstLetter != 'a' && firstLetter != 'e' && firstLetter != 'i' && firstLetter != 'o' && firstLetter != 'u' ) { len = strlen(pigLatinWord); pigLatinWord[len] = firstLetter; pigLatinWord[len+1] = '\0'; } strcat( pigLatinWord, "ay" ); return; }