Top Banner
Topic 20 Characters and Strings
52

20 Characters and Strings

Jan 22, 2016

Download

Documents

programming C++
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 20 Characters and Strings

Topic 20

Characters and Strings

Page 2: 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.

Page 3: 20 Characters and Strings

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]);

Page 4: 20 Characters and Strings

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>

Page 5: 20 Characters and Strings

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.

Page 6: 20 Characters and Strings

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)

Page 7: 20 Characters and Strings

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’))

Page 8: 20 Characters and Strings

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.

Page 9: 20 Characters and Strings

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");

Page 10: 20 Characters and Strings

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]);

Page 11: 20 Characters and Strings

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

Page 12: 20 Characters and Strings

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

Page 13: 20 Characters and Strings

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.

Page 14: 20 Characters and Strings

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.

Page 15: 20 Characters and Strings

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.

Page 16: 20 Characters and Strings

Strings versus Array of Characters

An array of

A string characters

Page 17: 20 Characters and Strings

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).

""

Page 18: 20 Characters and Strings

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

Page 19: 20 Characters and Strings

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

Page 20: 20 Characters and Strings

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

Page 21: 20 Characters and Strings

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.

Page 22: 20 Characters and Strings

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.

Page 23: 20 Characters and Strings

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

Page 24: 20 Characters and Strings

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

Page 25: 20 Characters and Strings

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

Page 26: 20 Characters and Strings

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 |

Page 27: 20 Characters and Strings

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] );

Page 28: 20 Characters and Strings

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

Page 29: 20 Characters and Strings

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 ).

Page 30: 20 Characters and Strings

String Input with Spaces

If a newline character is read, function gets

discards the character and replaces it with a null

character.

Example:

Page 31: 20 Characters and Strings

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>

Page 32: 20 Characters and Strings

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

Page 33: 20 Characters and Strings

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] )

Page 34: 20 Characters and Strings

String Functions – strcpy

The function strcpy copies the contents of one

string to another.

Example: strcpy( s1, s2 )

Page 35: 20 Characters and Strings

String Functions – strcpy

We can also copy part of the word.

Example: strcpy( s1, &s2[5] )

Page 36: 20 Characters and Strings

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’).

Page 37: 20 Characters and Strings

String Functions – strncpy

Example: strncpy( s1, s2, 8)

Page 38: 20 Characters and Strings

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.

Page 39: 20 Characters and Strings

String Functions – strcmp

1) If the two strings are equal, the function returns

0.

Page 40: 20 Characters and Strings

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).

Page 41: 20 Characters and Strings

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).

Page 42: 20 Characters and Strings

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

Page 43: 20 Characters and Strings

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.

Page 44: 20 Characters and Strings

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 )

Page 45: 20 Characters and Strings

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]);

Page 46: 20 Characters and Strings

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

Page 47: 20 Characters and Strings

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

Page 48: 20 Characters and Strings

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.

Page 49: 20 Characters and Strings

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.

Page 50: 20 Characters and Strings

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 }

Page 51: 20 Characters and Strings

Case Study 1 – Complete Program

void pig_latin(char word[], char pigLatinWord[]); { char firstLetter; int len; firstLetter = word[0]; strcpy( pigLatinWord, &word[1] );

Page 52: 20 Characters and Strings

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