Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 8: Characters Arrays (Strings) CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Similar presentations


Presentation on theme: "CHAPTER 8: Characters Arrays (Strings) CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)"— Presentation transcript:

1 CHAPTER 8: Characters Arrays (Strings) CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

2 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 2BS (May 2013)

3 MORE ABOUT CHARACTERS Topic 1 BS (May 2013)3

4 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 2013)4

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

6 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 (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 BS (May 2013)6

7 Example 1 BS (May 2013)7 #include 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 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 65 ASCII value for Z is 90 ASCII value for a is 97 ASCII value for z is in ASCII represents A 90 in ASCII represents Z 97 in ASCII represents a 122 in ASCII represents z

8 Example 2 BS (May 2013)8 #include void main(void) { char ch; printf(“Enter a character: "); scanf("%c", &ch); if (ch >= 'A' && ch <= 'Z') { printf("\nCapital Letter\n"); } #include void main(void) { char ch; printf(“Enter a character: "); scanf("%c", &ch); if (ch >= 'A' && ch <= 'Z') { printf("\nCapital Letter\n"); } #include void main(void) { char ch; printf(“Enter a character: "); scanf("%c", &ch); if (ch >= 65 && ch <= (65+26)) { printf("\nCapital Letter\n"); } #include void main(void) { char ch; printf(“Enter a character: "); scanf("%c", &ch); if (ch >= 65 && ch <= (65+26)) { printf("\nCapital Letter\n"); } Equivalent

9 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 in your program. Characters in these functions are manipulated as integers (since a character is basically a 1 byte integer). BS (May 2013)9

10 Functions in BS (May 2013)10 FunctionsDescriptions 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 value c is a digit, and 0 (false) otherwise.

11 Example BS (May 2013)11 #include 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 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: G The character is an alphabet and it is also an upper case alphabet Another character? [y = yeas, n = no]:y Enter a character: 50 The character is a digit Another character? [y = yeas, n = no]:n

12 FUNDAMENTALS OF STRINGS Topic 2 BS (May 2013)12

13 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 2013)13 char color[6] = “green”; char color[] = “green” char *color = “green

14 Strings – Technically 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 2013)14 g r e e n \0 color [0] [1] [2] [3] [4] [5] char color[6] = “green”; The NULL character indicates the end of the string

15 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 2013)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

16 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 2013)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: blue Chosen color: blue

17 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(). (May not work in certain OS –e.g., LINUX) BS (May 2013)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 Tuesday is what I received.

18 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: BS (May 2013)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

19 Finding the Length of A String Can be achieved in 2 ways: 1.Using a looping statement, as shown below: BS (May 2013)19 #include 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 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

20 Finding the Length of A String 2.Using strlen() function in the as shown in below example: BS (May 2013)20 #include void main(void) { char name[ ] = “Mona Lisa”; int x=0; x = strlen(name); printf(“There are %d characters in the name.”, x); } #include 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.

21 STANDARD OPERATIONS ON STRINGS Topic 3 BS (May 2013)21

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

23 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 2013)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 void main (void){ char copy[25], msg[25]=“The game is underway”; strcpy(copy,msg); printf(“The copied message: %s”, copy); } #include 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 s1 The contents of s1 after strcpy will be exactly the same as s2 Copies the whole of string s2 into the array s1 The contents of s1 after strcpy will be exactly the same as s2 The copied message: The game is underway

24 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 2013)24 #include 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 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 underway The 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. char *strncpy (char *s1, const char *s2, size_t n)

25 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 2013)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: -1 Difference 2: 1 Difference 3: 0

26 Comparing Strings - strncmp() To compare only certain number of characters of two strings, you need to use strncmp() function. The syntax: Example: BS (May 2013)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. #include void main (void) { char first[]="April", second[]="September"; int diff=0; diff=strncmp(first,"AprIL",3); if(diff==0) printf("Match found."); else printf("There is no match"); } #include void main (void) { char first[]="April", second[]="September"; int diff=0; diff=strncmp(first,"AprIL",3); if(diff==0) printf("Match found."); else printf("There is no match"); } Match found.

27 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 s1 is large enough to hold the entire contents of s2 as well as its own contents. Example: BS (May 2013)27 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. #include void main(void) { char str1[20] = "Hello", str2[] = "World"; strcat(str1, str2); printf(“First string:\n%s\n", str1); } #include void main(void) { char str1[20] = "Hello", str2[] = "World"; strcat(str1, str2); printf(“First string:\n%s\n", str1); } First string: HelloWorld

28 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 2013)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. #include 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 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

29 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 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: Your user ID code is ba0123 BS (May 2013)29

30 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, 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 2013)30 char hello[] = “9999”; atoi (“1234”); const char hello[] = “9999”; atoi(hello ); atoi (“1234”); const char hello[] = “9999”; atoi(hello );

31 String Conversion Functions BS (May 2013)31 Function PrototypePurpose 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).

32 Example BS (May 2013)32 //1. Converting a String Into an int Using atoi. #include 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 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

33 Character Handling in A String BS (May 2013)33 #include 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 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 pagi Hello malaysia 12 pagi has 17 alphabet, 2 digit and 3 space

34 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 Your sentence contains: Alphabets: 9 Digits: 8 Punctuations: 1 BS (May 2013)34

35 Summary 1.More about characters An integer digit vs. a character digit Character handling library in 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


Download ppt "CHAPTER 8: Characters Arrays (Strings) CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)"

Similar presentations


Ads by Google