Вы находитесь на странице: 1из 35

CHAPTER 8: Characters and

Strings
CSEB113 PRINCIPLES of
PROGRAMMING
by
Badariah Solemon

BS (May 2013)

Topics
1. More about characters

An integer digit vs. a character digit


Character handling library

2. Fundamentals of strings

What are strings?


Reading and displaying strings
Calculating length of strings

3. Standard operations with strings

Copying strings with strcpy() and strncpy()


Comparing strings with strcmp() and strncmp()
Concatenating strings with strcat() and strncat()
String conversions
BS (May 2013)

Topic 1
MORE ABOUT CHARACTERS
BS (May 2013)

Characters
Recall from Chapter 3 that characters in C consist of
any printable or nonprintable character in the
computers character set including lowercase letters,
uppercase letters, decimal digits, special characters
and escape sequences.
A character is usually stored in the computer as an 8bits (1 byte) integer.
The integer value stored for a character depends on
the character set used by the computer on which the
program is running.
Two commonly used character sets:
ASCII (American Standard Code for Information
Interchange)
EBCDIC (Extended Binary Coded Decimal Interchange
Code)
BS (May 2013)

ASCII Character Set

In ASCII, for example, the code for A is 65 and z is


122. The blank character is denoted by
.
BS (May 2013)

Integer Digit vs. Character


Digit

char num = 1; and char num = 1;

are not the same.


char num = 1; is represented in the
computer as 00000001 (i.e. number 1).
char num = 1; on the other hand is
number 49 according to the ASCII
character set. Therefore, it is
represented in the computer as
00110001.

BS (May 2013)

Example1
#include <stdio.h>
void main(void)
{
char my_A = 'A';
char my_Z = 'Z';
char my_a = 'a';
char my_z = 'z';
printf("\nASCII
printf("\nASCII
printf("\nASCII
printf("\nASCII

ASCII
ASCII
ASCII
ASCII

value
value
value
value

for
for
for
for

A
Z
a
z

is
is
is
is

65
90
97
122

65 in ASCII represents A
90 in ASCII represents Z
97 in ASCII represents a
122 in ASCII represents z

value
value
value
value

for
for
for
for

A
Z
a
z

is
is
is
is

%d", my_A);
%d",my_Z);
%d", my_a);
%d",my_z);

printf("\n");
printf("\n65 in ASCII represents %c",65);
printf("\n90 in ASCII represents %c",90);
printf("\n97 in ASCII represents %c",97);
printf("\n122 in ASCII represents %c\n",122);
BS (May 2013)

Example2
#include <stdio.h>

#include <stdio.h>

void main(void)
{
char ch;

void main(void)
{
char ch;
printf(Enter a character: ");
scanf("%c", &ch);

if (ch >= 'A' && ch <= 'Z')


{
printf("\nCapital Letter\n");
}

if (ch >= 65 && ch <= (65+26))


{
printf("\nCapital Letter\n");
}

printf(Enter a character: ");


scanf("%c", &ch);

Equivalent
BS (May 2013)

Character Handling Library


Includes several functions that perform useful
tests and manipulation of character data.
Each function receives a character,
represented as an int or EOF, as an
argument.
To use the functions from the character
handling library, include header file #include
<ctype.h> in your program.
Characters in these functions are
manipulated as integers (since a character is
basically a 1 byte integer).
BS (May 2013)

Functions in <ctype.h>
Functions

Descriptions

int isdigit(int c)

Returns a true if value c is a digit, and 0 (false) otherwise.

int isalpha(int c)

Returns a true if value c is a letter, and 0 otherwise.

int isalnum(int c)

Returns a true if value c is a digit or a letter, and 0 otherwise.

int isxdigit(int c)

Returns a true value if c is a hexadecimal digit character, and 0 otherwise.

int islower(int c)

Returns a true value if c is a lowercase letter, and 0 otherwise.

int isupper(int c)

Returns a true value if c is an uppercase letter, and 0 otherwise.

int tolower(int c)

If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise,


tolower returns the argument unchanged.

int toupper(int c)

If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise


toupper returns the argument unchanged.

int isspace(int c)

Returns true if c is a white space character newline (\n), space ( ), form feed
(\f), carriage return (\r), horizontal tab (\t) or vertical tab (\v) and 0
otherwise.

int iscntrl(int c)

Returns a true if c is a control character, and 0 otherwise.

int ispunct(int c)

Returns a true if c is a printing character other than a space, a digit or a letter, and
0 otherwise.

int isprint(int c)

Returns a true value if c is a printing character including space ( ), and 0


otherwise.

int isgraph(int c)

Returns a true value if c is a printing character other than space ( ), and 0


otherwise.

int isdigit(int c)

Returns a true if valueBS


c is
a digit,
and 0 (false) otherwise.
(May
2013)

10

Example
Enter a character: G
#include <ctype.h>
The character is an alphabet
void main(void)
and it is also an upper case alphabet
{
char loop = 'y, myChar;
Another character? [y = yeas, n = no]:y
while (loop == 'y' || loop == 'Y')
{
Enter a character: 50
fflush(stdin);
The character is a digit
printf("Enter a character: ");
Another character? [y = yeas, n = no]:n
myChar = getchar();
if (isalpha(myChar))
{
printf("The character is an alphabet\n");
if (islower(myChar))
printf("and it is also a lower case alphabet\n");
if (isupper(myChar))
printf("and it is also an upper case alphabet\n");
}
if (isdigit(myChar))
printf("The character is a digit\n");
if (ispunct(myChar))
printf("The character is a punctuator\n");
fflush(stdin);
printf("\nanother character? [y = yes, n = no]: ");
loop = getchar();
printf("\n");
}
BS (May 2013)
11
}

Topic 2
FUNDAMENTALS OF STRINGS
BS (May 2013)

12

What is A String
A string (or character string) is simply a sequence
of characters such as persons name, address,
city and etc.
Just like any other data types, string may be read,
processed and displayed. However, string is not a
data type.
A string in C is a special kind of 1-D array of
characters ending with the null character (\0).
It is written inside a double quotation mark (" ")
A string
may
be assign
in a declaration to either a
char
color[6]
= green;
char color[]
green
char array
or to a= char
pointer as follows:
char *color = green

BS (May 2013)

13

Strings Technically
Given this declaration:
char color[6] = green;

In memory, these are the characters stored as follows:


[0]

color g

[1] [2] [3] [4] [5]

The NULL character


\0indicates the end of the
string

Notice that even though there are only five characters


in the word green, six characters are stored in the
computer..
Therefore, if an array of characters is to be used to
store a string, the array must be large enough to store
the string and its terminating NULL character.
BS (May 2013)

14

Initializing A String
We can initialize string variables at compile
time such as:
char name1[10] = Arris;

This initialization creates the following


spaces in
The first NULL
storage
name1
A r : r i s \0 \0 \0 \0 \0 character
terminates the
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] string

Syntax error: error C2117: 'tea' : array bounds overflow

So:
char myDrink[3] = tea;
(the
size of the string
+ 1) to
char
myDrink[4]
= tea;

accommodate the null terminating


character \0
BS (May 2013)

15

Reading and Displaying A String scanf()


and printf()
Using %s format specifier. Example:
char color[6];
printf("Enter color:");
scanf("%s", &color);

Enter color: blue


Chosen color: blue

printf("Chosen color: %s", color);

However, the program will show weird


behaviour if:
There is a white space or more than one word in
Enter color: light blue
the string.
Only the first word is stored
color:
magenta
The user enterEnter
a color
longer
than 5 characters
BS (May 2013)

16

Reading and Displaying A String gets() and


puts()
The functions gets() and puts() are exclusively
designed to read and display strings only
The gets() function can be used to read more than
one words unlike scanf().
Enter some message:
We are closed on Tuesday
Example:
char msg[30];
char msg[30];

printf("Enter some message:");


fflush(stdin);
gets(msg);

The following:
We are closed on Tuesday
is what I received.

printf("\nThe following: ");


puts(msg);
puts("is what I received. ");

Use fflush(stdin) to remove any leftover data in the


buffer prior to calling gets(). (May not work in certain OS e.g., LINUX)
BS (May 2013)

17

String Length vs. String


Array
Size
The length of a string is the count of the number

of characters preceding the first null character.


Observe these examples:
char name1[10]=Lisa;
//The size of array name1 is 10
//but the string lengthy is 4
char name2[ ]=Monas;
//The string lengthy is 5
//So, the array size is
//the string length + 1 null character = 6
char name3[ ];
//This type of declaration should be avoided
//because the compiler does not know
//what size to give to the array
BS (May 2013)

18

Finding the Length of A


String

Can be achieved in 2 ways:

1. Using a looping statement, as shown below:


#include <stdio.h>
void main(void)
{
char sentence[] = "I love Malaysia";
int i, count = 0;

the

for (i = 0; sentence[i] != '\0'; i++)


{
count++;
}
printf("%s has %d characters including
whitespace\n", sentence, count);

}
I love Malaysia has 15 characters including the whitespace
BS (May 2013)

19

Finding the Length of A


String
2. Using strlen() function in the <string.h>
as shown in below example:

#include <stdio.h>
#include <string.h>
void main(void)
{
char name[ ] = "Mona Lisa";
int x=0;
x = strlen(name);
printf("There are %d characters in the name. ",
x);
}
There are 9 characters in the name.

BS (May 2013)

20

Topic 3
STANDARD OPERATIONS ON
STRINGS
BS (May 2013)

21

Operations on Strings
The standard C library comes with a long list
of functions to perform operations on strings.
To use the functions, include the :
#include <string.h> in your program.
The standard functions covered in this
course include:
Copying strings with strcpy() and strncpy()
Comparing strings with strcmp() and strncmp()
Concatenating strings with strcat() and
strncat()

BS (May 2013)

22

Copying Strings - strcpy()


Unlike the char variable, you cannot assign a
string to the character string variable . This
char initial;
char name[30];
means:

initial = B;
name=Badariah Solemon;
initial = B;

name=Badariah Solemon;

Instead, you could copy one string to another


using char
the strcpy()
function
. The
syntax:
*strcpy (char
*s1,
const
char *s2)
Copies the whole of string s2 into the array s1
The contents of s1 after strcpy will be exactly the
same as s2

For
example:
#include
<string.h>

The copied message: The game is underway


#include <stdio.h>
void main (void){
char copy[25], msg[25]=The game is underway;

strcpy(copy,msg);
printf(The copied message: %s, copy);
BS (May 2013)

23

Copying Strings - strncpy()


The strcpy() is used to copy the whole string
to another.
To copy only certain number of characters
from one string to another, you need to use
char *strncpy (char *s1,
char *s2, size_t n)
strncpy()function.
The const
syntax:
Copies at most n characters of the
string s2 into the array s1. The value
of s1 is returned.
The first copy gave: The game is underway

#include <string.h>
The second copy gave: The game is
#include <stdio.h>
void main (void){
Observe
this example:
char copy[25], msg[25]=The game is underway;
strcpy(copy, msg);
printf(The first copy gave: %s, copy);

strncpy(copy, msg, 11);


printf(The second copy gave: %s, copy);
BS (May 2013)

24

Comparing Strings strcmp()


The strcmp() and strncat()functions allow us to compare
two strings. Both are case-sensitive.
The strcmp() can be used to compare if two strings are
identical. The syntax:
int strcmp (const char *s1, const char *s2);

Example:
Difference 1: -1
Difference 2: 1
Difference 3: 0

Accepts two strings and returns an integer. This


integer is:
Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.
char first[]=April, second[]=August;
int diff=0;
diff=strcmp(first,second);
printf(Difference 1: %d\n, diff);
diff=strcmp(first,APRIL);
printf(Difference 2: %d\n, diff);
diff=strcmp(August,second);
printf(Difference 3: %d\n, diff);
BS (May 2013)

25

Comparing Strings strncmp()

To compare only certain number of characters


of two strings, you need to use
strncmp()function. The syntax:
int strncmp (const char *s1, const char *s2, size_t
n)
compares up to n characters of the string s1 to
the string s2.

#include <string.h>
#include <stdio.h>
Example: void main (void)
{
char first[]="April", second[]="September";
int diff=0;

Match found.

diff=strncmp(first,"AprIL",3);
if(diff==0)
printf("Match found.");
else
printf("There is no match");
BS (May 2013)

26

Concatenating Strings strcat()

strcat is short for string concatenate, which


means to add to the end, or append. The syntax:
char *strcat ( char *s1, const char *s2);
It appends the string s2 to the array s1. The first character of
s2 overwrites the terminating NULL character of s1. The value
of s1 is returned.

Beware, this function assumes that s1is large enough to


hold the entire contents of s2 as well as its own
contents. #include <stdio.h>

Example:
First string:
HelloWorld

#include <string.h>
void main(void)
{
char str1[20] = "Hello", str2[] = "World";
strcat(str1, str2);
printf(First string:\n%s\n", str1);
}
BS (May 2013)

27

Concatenating Strings strncat()

To append certain number of characters from one


string to another, you may use the strncat()
function. The syntax:
char *strncat (char *s1, const char *s2, size_t n);
Appends at most n characters of string s2 to array s1. The first
character of s2 overwrites the terminating NULL character of s1.
The value of s1 is returned.
#include <stdio.h>
Example: #include <string.h>
void main(void)
{
Second append:
char str1[20] = "Mexico", str2[] = "Russia";
Mexico Russ
char str3[]= "Japan";
Third append:
strcat(str1, " ");
Mexico RussJap
strncat(str1, str2, 4);
printf(Second append:\n%s\n", str1);
strncat(str1, str3, 3);
printf(\nThird append:\n%s\n", str1);
}
BS (May 2013)

28

Test Your Skill


Write a program that prompts the user to
enter his/her name and a phone
number.
Then construct a user ID
code by combining the first 2 letters of the
users name and followed by the first 4
digits of the phone number. Then, display
the user ID code.

Example output:
Enter your name: badariah
Enter your phone number: 0123453862
Your user ID code is ba0123
BS (May 2013)

29

Strings Conversion
If you have a string of digits such as below:
char hello[]

= 9999;

you may convert the string to integer and floatingpoint values by using strings conversion
functions.

To use these functions, the general utilities


library <stdlib.h>, needs to be included.
These functions take a constant value as
their argument. This means that we can only
pass a constant
string to the functions.
atoi (1234);
Example:
const char hello[]
atoi(hello);
BS (May 2013)

= 9999;

30

String Conversion Functions


Function Prototype

Purpose

double atof (const char *nPtr)

Converts the sting nPtr to


double.

int atoi (const char *nPtr)

Converts the string nPtr to


int.

long atol (const char *nPtr)

Converts the string nPtr to


long int.

double strtod (const char *nPtr, char **endptr)

Converts the string nPtr to


double.

long strtol (const char *nPtr, char **endptr,


int base)

Converts the string nPtr


long.

nPtr
- The pointer to the string to be converted.
endptr - The pointer to which the remainder of the string will be
assigned after the conversion. We can pass a NULL if the remaining
string is to be ignored.
base
- Indicates the format (base) of the string to be converted. If 0 is
given, that means the value to be converted can be in octal (base 8),
decimal (base 10) or hexadecimal
(base
16).
BS (May
2013)
31

Example
//1. Converting a String Into an int Using atoi.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char str1[] = "124z3yu87";
char str2[] = "-3.4";
char str3[] = "e24";
printf("str1: %d\n", atoi(str1));
printf("str2: %d\n", atoi(str2));
printf("str3: %d\n", atoi(str3));
}
str1: 124
str2: -3
str3: 0

BS (May 2013)

32

Character Handling in A
String

#include <ctype.h>
#include <string.h>
Enter a string: hello malaysia 12 pagi
void main(void)
Hello malaysia 12 pagi has 17 alphabet, 2 digit and 3 space
{
char string[50];
int length, i, alpha = 0, digit = 0, space = 0;
printf("Enter a string: ");
gets(string);
length = strlen(string);
for (i = 0; i < length; i++)
{
if (isalpha(string[i]))
alpha++;
if (isdigit(string[i]))
digit++;
if (isspace(string[i]))
space++;
}
printf("%s has %d alphabet, %d digits and %d spaces
\n",string,alpha,digit,space);
}

BS (May 2013)

33

Test Your Skill


Write program that will count the number
of alphabets, digits and
punctuations in a
sentence given by
the user.
Example output:
Enter your sentence: my tel no is 12345678.

Your sentence contains:


Alphabets: 9
Digits: 8
Punctuations: 1

BS (May 2013)

34

Summary
1. More about characters

An integer digit vs. a character digit


Character handling library in <ctype.h>

2. Fundamentals of strings

string in C is a special kind of 1-D array of characters ending


with the null character (\0). It is written inside a double
quotation mark ( )
Reading and displaying strings using scanf(), gets(),
printf(), puts()
Calculating length of strings using strlen().

3. Standard operations with strings

Copying strings with strcpy() and strncpy()


Comparing strings with strcmp() and strncmp()
Concatenating strings with strcat() and strncat()
String conversions functions and character handling of a string
BS (May 2013)

35

Вам также может понравиться