35
CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1 BS (May 2012)

CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Embed Size (px)

Citation preview

Page 1: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

CHAPTER 8: Characters and Strings

CSEB113 PRINCIPLES of PROGRAMMING CSEB134

PROGRAMMING I

byBadariah Solemon

1BS (May 2012)

Page 2: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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

2BS (May 2012)

Page 3: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

MORE ABOUT CHARACTERS

Topic 1

BS (May 2012) 3

Page 4: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Characters• Recall from Chapter 3 that characters in C consist of any

printable or nonprintable character in the computer’s character set including lowercase letters, uppercase letters, decimal digits, special characters and escape sequences.

• A character is usually stored in the computer as an 8-bits (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 2012) 4

Page 5: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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 2012) 5

Page 6: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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 2012) 6

Page 7: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Example

BS (May 2012) 7

#include <stdio.h>void main(void){

char my_A = 'A';char my_Z = 'Z';char my_a = 'a';char my_z = 'z';

printf("\nASCII value for A is %d", my_A);printf("\nASCII value for Z is %d",my_Z);printf("\nASCII value for a is %d", my_a);printf("\nASCII value for z is %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);

}

#include <stdio.h>void main(void){

char my_A = 'A';char my_Z = 'Z';char my_a = 'a';char my_z = 'z';

printf("\nASCII value for A is %d", my_A);printf("\nASCII value for Z is %d",my_Z);printf("\nASCII value for a is %d", my_a);printf("\nASCII value for z is %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);

}

ASCII value for A is 65ASCII value for Z is 90ASCII value for a is 97ASCII value for z is 122

65 in ASCII represents A90 in ASCII represents Z97 in ASCII represents a122 in ASCII represents z

Page 8: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

More Example

BS (May 2012) 8

#include <stdio.h> void main(void){ char ch;  printf(“Enter a character: "); scanf("%c", &ch);  if (ch >= 'A' && ch <= 'Z') {

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

#include <stdio.h> void main(void){ char ch;  printf(“Enter a character: "); scanf("%c", &ch);  if (ch >= 'A' && ch <= 'Z') {

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

#include <stdio.h> void main(void){ char ch;  printf(“Enter a character: "); scanf("%c", &ch);  if (ch >= 65 && ch <= (65+26)) { printf("\nCapital Letter\n"); }}

#include <stdio.h> void main(void){ char ch;  printf(“Enter a character: "); scanf("%c", &ch);  if (ch >= 65 && ch <= (65+26)) { printf("\nCapital Letter\n"); }}

Equivalent

Page 9: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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 2012) 9

Page 10: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Functions in <ctype.h>

BS (May 2012) 10

Functions Descriptionsint 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 value c is a digit, and 0 (false) otherwise.

Page 11: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Example

BS (May 2012) 11

#include <ctype.h>

void main(void)

{

char loop = 'y’, myChar;

while (loop == 'y' || loop == 'Y')

{

fflush(stdin);

printf("Enter a character: ");

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

}

}

#include <ctype.h>

void main(void)

{

char loop = 'y’, myChar;

while (loop == 'y' || loop == 'Y')

{

fflush(stdin);

printf("Enter a character: ");

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

}

}

Enter a character: GThe character is an alphabetand it is also an upper case alphabet

Another character? [y = yeas, n = no]:y

Enter a character: 50The character is a digit

Another character? [y = yeas, n = no]:n

Page 12: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

FUNDAMENTALS OF STRINGS

Topic 2

BS (May 2012) 12

Page 13: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

What is A String• A string (or character string) is simply a sequence of

characters such as person’s 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 array or to a char pointer as follows:

BS (May 2012) 13

char color[6] = “green”;char color[] = “green” char *color = “green

Page 14: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

String – Technical Discussion

• Given this declaration:

• In memory, these are the characters stored as follows:

• 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 2012) 14

g r e e n \0color

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

char color[6] = “green”;char color[6] = “green”;

The NULL character indicates the end of the string

Page 15: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Initializing A String• We can initialize string variables at compile time such as:

char name1[10] = “Arris”;

• This initialization creates the following spaces in storage :

• So:char myDrink[3] = “tea”;

char myDrink[4] = “tea”;

BS (May 2012) 15

(the size of the string + 1) to accommodate the null terminating character ‘\0’

A r r i s \0 \0 \0 \0 \0

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

name1

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

The first NULL character terminates the string

Page 16: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Reading and Displaying A String – scanf() and printf()

• Using %s format specifier. Example:

• However, the program will show weird behaviour if:– There is a white space or more than one word in the string.

• Only the first word is stored

– The user enter a color longer than 5 characters

BS (May 2012) 16

char color[6];

printf(“Enter color:”);scanf(“%s”, &color);

printf(“Chosen color: %s”, color);

char color[6];

printf(“Enter color:”);scanf(“%s”, &color);

printf(“Chosen color: %s”, color);

Enter color: light blue

Enter color: magenta

Enter color: blueChosen color: blue

Page 17: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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

• Example:

• Use fflush(stdin) to remove any leftover data in the buffer prior to calling gets().

BS (May 2012) 17

char msg[30];

printf(“Enter some message:”);fflush(stdin);gets(msg);

printf(“\nThe following: ”);puts(msg);

puts(“is what I received.”);

char msg[30];

printf(“Enter some message:”);fflush(stdin);gets(msg);

printf(“\nThe following: ”);puts(msg);

puts(“is what I received.”);

Enter some message:We are closed on Tuesday

The following:We are closed on Tuesdayis what I received.

Page 18: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

String Length vs. Its Array Size

• The length of a string is the count of the number of characters preceding the first null character.

• Observe these examples:

BS (May 2012) 18

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

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

Page 19: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Finding the Length of A String

• Can be achieved in 2 ways: 1. Using a looping statement, as shown below:

BS (May 2012) 19

#include <stdio.h>void main(void){

char sentence[] = "I love Malaysia";int i, count = 0;

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

count++;}printf(“%s has %d characters including

the whitespace\n", sentence, count);

}

#include <stdio.h>void main(void){

char sentence[] = "I love Malaysia";int i, count = 0;

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

count++;}printf(“%s has %d characters including

the whitespace\n", sentence, count);

}

I love Malaysia has 15 characters including the whitespace

Page 20: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Finding the Length of A String

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

BS (May 2012) 20

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

}

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

Page 21: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

STANDARD OPERATIONS ON STRINGS

Topic 3

BS (May 2012) 21

Page 22: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Operations on Arrays• The standard C library comes with a long list of string

functions to perform operations on arrays.• 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 2012) 22

Page 23: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Copying Strings - strcpy() • Unlike the char variable, you cannot assign a string to the

character string variable . This means:

• Instead, you could copy one string to another using the strcpy() function. The syntax:

• For example:

BS (May 2012) 23

char initial;initial = ‘B’;char initial;initial = ‘B’;

char name[30]; name=“Badariah Solemon”;char name[30]; name=“Badariah Solemon”;

char *strcpy (char *s1, const char *s2)

#include <string.h>#include <stdio.h>void main (void){

char copy[25], msg[25]=“The game is underway”;

strcpy(copy,msg);printf(“The copied message: %s”, copy);

}

#include <string.h>#include <stdio.h>void main (void){

char copy[25], msg[25]=“The game is underway”;

strcpy(copy,msg);printf(“The copied message: %s”, copy);

}

Copies the whole of string s2 into the array s1The contents of s1 after strcpy will be exactly the same as s2Copies the whole of string s2 into the array s1The contents of s1 after strcpy will be exactly the same as s2

The copied message: The game is underway

Page 24: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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 strncpy()function. The syntax:

• Observe this example:

BS (May 2012) 24

#include <string.h>#include <stdio.h>void main (void){

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

}

#include <string.h>#include <stdio.h>void main (void){

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

}

The first copy gave: The game is underwayThe second copy gave: The game is

Copies at most n characters of the string s2 into the array s1. The value of s1 is returned.Copies at most n characters of the string s2 into the array s1. The value of s1 is returned.

char *strncpy (char *s1, const char *s2, size_t n)

Page 25: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

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:

• Example:

BS (May 2012) 25

int strcmp (const char *s1, const char *s2);

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.

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

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

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

Page 26: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Comparing Strings - strncmp()

• To compare only certain number of characters of two strings, you need to use strncmp()function. The syntax:

• Example:

BS (May 2012) 26

int strncmp (const char *s1, const char *s2, size_t n)

compares up to n characters of the string s1 to the string s2.compares up to n characters of the string s1 to the string s2.

#include <string.h>#include <stdio.h>void main (void){

char first[]="April", second[]="September";int diff=0;

diff=strncmp(first,"AprIL",3);if(diff==0)

printf("Match found.");elseprintf("There is no match");

}

#include <string.h>#include <stdio.h>void main (void){

char first[]="April", second[]="September";int diff=0;

diff=strncmp(first,"AprIL",3);if(diff==0)

printf("Match found.");elseprintf("There is no match");

}

Match found.

Page 27: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Concatenating Strings - strcat()

• strcat is short for string concatenate, which means to add to the end, or append. The syntax:

– Beware, this function assumes that s1is large enough to hold the entire contents of s2 as well as its own contents.

• Example:

BS (May 2012) 27

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

#include <stdio.h> #include <string.h> void main(void){

char str1[20] = "Hello", str2[] = "World"; strcat(str1, str2); printf(“First string:\n%s\n", str1);

}

#include <stdio.h> #include <string.h> void main(void){

char str1[20] = "Hello", str2[] = "World"; strcat(str1, str2); printf(“First string:\n%s\n", str1);

}

First string:HelloWorld

Page 28: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Concatenating Strings - strncat()

• To append certain number of characters from one string to another, you may use the strncat() function. The syntax:

• Example:

BS (May 2012) 28

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.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> #include <string.h> void main(void){

char str1[20] = "Mexico", str2[] = "Russia"; char str3[]= "Japan";

strcat(str1, " "); strncat(str1, str2, 4);

printf(“Second append:\n%s\n", str1); strncat(str1, str3, 3); printf(“\nThird append:\n%s\n", str1);}

#include <stdio.h> #include <string.h> void main(void){

char str1[20] = "Mexico", str2[] = "Russia"; char str3[]= "Japan";

strcat(str1, " "); strncat(str1, str2, 4);

printf(“Second append:\n%s\n", str1); strncat(str1, str3, 3); printf(“\nThird append:\n%s\n", str1);}

Second append:Mexico Russ

Third append:Mexico RussJap

Page 29: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Exercise• 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 user’s 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 2012) 29

Page 30: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Strings Conversion• If you have a string of digits such as below:

you may convert the string to integer and floating-point 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.

• Example:

BS (May 2012) 30

char hello[] = “9999”;char hello[] = “9999”;

atoi (“1234”);

const char hello[] = “9999”;atoi(hello);

atoi (“1234”);

const char hello[] = “9999”;atoi(hello);

Page 31: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

String Conversion Functions

BS (May 2012) 31

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

Page 32: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Example

BS (May 2012) 32

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

}

//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: 124str2: -3str3: 0

Page 33: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Character Handling in A String

BS (May 2012) 33

#include <ctype.h>

#include <string.h>

void main(void)

{

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

}

#include <ctype.h>

#include <string.h>

void main(void)

{

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

}

Enter a string: hello malaysia 12 pagiHello malaysia 12 pagi has 17 alphabet, 2 digit and 3 space

Page 34: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Exercise• 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: 9Digits: 8Punctuations: 1

BS (May 2012) 34

Page 35: CHAPTER 8: Characters and Strings CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (May 2012)

Summary1. 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 2012) 35