1 / 43

EKT120 COMPUTER PROGRAMMING

EKT120 COMPUTER PROGRAMMING. Arrays & Strings (Part II) Dr. Nik Adilah Hanin Bt. Zahri adilahhanin@unimap.edu.my. Recaps… What is Array?. An array is a collection of a fixed number of components wherein all of the components are of the same type

kat
Download Presentation

EKT120 COMPUTER PROGRAMMING

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. EKT120COMPUTER PROGRAMMING Arrays & Strings (Part II) Dr. NikAdilahHanin Bt. Zahri adilahhanin@unimap.edu.my

  2. Recaps… What is Array? • An array is a collection of a fixed number of components wherein all of the components are of the same type • Example: Suppose that there is a list of five integers: 5, 10, 15, 20, and 25 • Previously we would declare five variables: int iNum1,iNum2,iNum3,iNum4,iNum5; • By using array, since they are all of the same data type, we could just write: intaiNum[5];

  3. Recaps… What is Array? aiNum • intaiNum[5]; • 5 components or elements in this array • Elements are referred to index • Element aiNum[2] has index 2 and value 15 aiNum[0] aiNum[1] aiNum[2] aiNum[3] aiNum[4]

  4. Recaps… 2-Dimensional Array intaiValue[4][2]; aiValue[2][1]=5; Column 0 1 0 1 2 3 Row

  5. Recaps… 2-Dimensional Array intaiValue[4][2]; aiValue[2][1]=5; Column 0 1 0 1 2 3 Row

  6. Outline • Introduction to Strings • Declaration of Strings • Fundamentals of Strings & Characters • Initialization of Strings • Assigning Values to Strings • Character and String Manipulations • Strings Conversion Functions • ASCII Table

  7. What is a String? • A string is a series of characters treated as a single unit. • Also known as character array • Strings can be treated as array of type char used to store names of people, places, or anything that involves a combination of letters. • A string may include letters, digits and various special characters such as +, -, *, ? and $. • String literals, or string constants, in C are written in double quotation marks ( “ ” ) as follows: Example: “John Doe” (a name) “99999 Main Street” (a street address) “Kangar, Perlis” (a city and a state) “(012) 123-8755” (a telephone number)

  8. What is a String? • The data type string is a programmer-defined and is not part of the C language • A string with no characters is called a null or empty string. “ ” is the empty string. • Every character in a string has a relative position in the string. • The position of the first character is 0, position of the second is 1, and so on. • The length of a string is the number of character in it. of a string is the address of its first character.

  9. Example String Position of a Character Length of the String in the String “William Jacob” Position of ‘W’ is 0 13 Position of the first ‘i’ is 1 Position of ‘ ’ (the space) is 7 Position of ‘J’ is 8 Position of ‘b’ is 12 “Mickey” Position of ‘M’ is 0 6 Position of ‘i’ is 1 Position of ‘c’ is 2 Position of ‘k’ is 3 Position of ‘e’ is 4 Position of ‘y’ is 5

  10. Declaration of Strings • Declaration of string/character array char variable_name[length]; • An example of declaration of an array (or string of characters): char name[10]; //declaration • can use to store “William”, “John Doe” etc and all strings that shorter than defined length • It is not necessary that this max size of 10 characters should at all the times fully used • The last value in the string will be a null character (‘\0’). char name[10]; can store a string up to 10 characters long, and may visualize it as below name

  11. Declaration of Strings (cont…) • name is an array of 10 elements of type char,could be represented by storing the strings of characters, e.g. “William” and “John Doe” in the following way: name W i l l i a m \0 to indicate end of string indefinite values J o h n D o e \0

  12. Declaration of Strings (cont…) • Also can be declared as a character array or a variable of type char * char name[] = “William"; char *name = “William";

  13. Formatted Input/ Output • Formatted input • Use scanf scanf("%s", name); • Copies input into name[] • Does not need & (because a string is a pointer) • Remember to leave room in the array for the null character ('\0’) • Formatted output • Use printf printf(“%s”,name);

  14. Example : Input and Output of String • Input and output characters using scanf() andprintf() • Example program: #include<stdio.h> int main() { char name[30]; printf("Enter name: "); scanf(“%s”,name); //read string from user printf(“Hi %s\n“,name); //display string return 0; }

  15. Initialization of String • Similar to array, but each character is enclosed in ‘ ’ or “ ”. • Example: • char newString[]={‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’}; • char newString[]= “Welcome”; • ‘\0’ is automatically inserted • The difference is that single quotes (‘) are used to specify single character constants and null character must be added at the end of the sentence. char newString[]= {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’}; Single quotes – null char must be added

  16. Initialization of String • On the other hand, double quotes (“) are constant that specify sequence of characters andalways have a null character (‘\0’) automatically inserted at the end. char newString[] = “Welcome”; Double quotes – null char automatically inserted

  17. Initialization of String (cont…) • The examples below are NOT VALIDfor string / characters array. newString = “Welcome”; //no [] and data type newString [] =“Welcome”; //no data type newString = {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’}; //no [] and data type

  18. Assigning Values to String • The left hand side value of an assignation can only be array items and not the entire array, a possible way to assign a string of characters to an array of charcan be shown as: newString[0] = ‘W’; newString[1] = ‘e’; newString[2] = ‘l’; newString[3] = ‘c’; newString[4] = ‘o’; newString[5] = ‘m’; newString[6] = ‘e’; newString[7] = ‘\0’;

  19. Character and String Manipulation • A program may need to verify/perform, e.g. • Calculation of the string size • Copy one string to another • Appends one string to another • Built-in functions available – makes it easier. • Standard input/output library <stdio.h> • General utilities library <stdlib.h> • Character handling library <ctype.h> • String handling library <string.h>

  20. Example 1: Input and Output of String • Input and output characters using gets() puts() function from <stdio.h> • Example program: #include<stdio.h> int main() { char name[30]; printf("Enter name: "); gets(name); //Function to read string from user printf(“Hi "); puts(name); //Function to display string return 0; }

  21. Example 1: Input and Output of String • Input and output characters using gets() puts() function from <stdio.h> • Example program: #include<stdio.h> int main() { char name[30]; printf("Enter name: "); gets(name); //Function to read string from user printf(“Hi "); puts(name); //Function to display string return 0; } Enter name : John Hi John

  22. Example 2: Input and Output of String • Input and output characters using gets() puts() function from <stdio.h> • Example program: #include<stdio.h> int main() { char name[3][30]; printf("Enter 3 names:\n"); for(i=0;i<3;i++) gets(name[i]); //Function to read string from user printf(“\nName Entered:\n”); for(i=0;i<3;i++) puts(name[i]); //Function to display string return 0; }

  23. Example 2: Input and Output of String • Input and output characters using gets() puts() function from <stdio.h> • Example program: #include<stdio.h> int main() { char name[3][30]; printf("Enter 3 names:\n"); for(i=0;i<3;i++) gets(name[i]); //Function to read string from user printf(“\nName Entered:\n”); for(i=0;i<3;i++) puts(name[i]); //Function to display string return 0; } Enter 3 names: Michael John Sarah Names Entered: Michael John Sarah

  24. Example 3: Calculation of String Size • Calculation of string size using strlen(char *string)function from <string.h> • char is 1 byte, the total number of alphabets would be the size of the string. • Example program: #include <stdio.h> #include <string.h> char newString1[] = {'W','e','l','c','o','m','e','\0'}; char newString2[] = "Good Bye"; int main() { //size of string Welcome printf ("Size of ‘%s’ is %d\n", newString1,strlen(newString1); //size of string Good Bye printf ("\nSize of ‘%s’ is %d\n",newString2,strlen(newString2)); return 0; }

  25. Example 3: Calculation of String Size • Calculation of string size using strlen(char *string)function from <string.h> • char is 1 byte, the total number of alphabets would be the size of the string. • Example program: #include <stdio.h> #include <string.h> char newString1[] = {'W','e','l','c','o','m','e','\0'}; char newString2[] = "Good Bye"; int main() { //size of string Welcome printf ("Size of ‘%s’ is %d\n", newString1,strlen(newString1); //size of string Good Bye printf ("\nSize of ‘%s’ is %d\n",newString2,strlen(newString2)); return 0; } Size of `Welcome’ is 7 Size of `Good Bye’ is 8

  26. Example 4: Controlling Case of a Character • In C, upper case letter, e.g. ‘K’ is not equal to lower case ‘k’ • So in C programming, you usually use: if (cChoice == ‘K’ || cChoice == ‘k’), OR while (cChoice == ‘Y’ || cChoice == ‘y’) • The case of a character can be controlled using tolower() and toupper() functions from <ctype.h> • temporarily converts a letter/char to uppercase or lowercase before comparing it toupper(int c) tolower(int c) • Also, can use functions that converts the whole string to upper or lowercase from <string.h> strupr(char *string) strlwr(char *string)

  27. Example 4: Controlling Case of a Character … char cChoice; printf ( “Continue? (Y or N) : “); scanf (“%c”, &cChoice); while(tolower(choice)=='y') { … … scanf("%s",&choice); } …

  28. Example 5: Controlling Case of a Character //To convert a string to uppercase #include <stdio.h> #include <string.h> void main() { char acName[20]; //declare an array of //characters 0-79 printf("Enter in a name in lowercase\n"); scanf( "%s", acName ); strupr(acName); printf("The name in uppercase is %s", acName ); }

  29. Example 5: Controlling Case of a Character //To convert a string to uppercase #include <stdio.h> #include <string.h> void main() { char acName[20]; //declare an array of //characters 0-79 printf("Enter in a name in lowercase\n"); scanf( "%s", acName ); strupr(acName); printf("The name in uppercase is %s", acName ); } Enter in a name in lowercase john The name in uppercase is JOHN

  30. Example 6: Controlling Case of a Character //To convert a string to uppercase #include <stdio.h> #include <ctype.h> int main() { inti=0; char line[]= "my NAME is JOHN"; printf(“Before conversion : %s\n",line); i=0; while (line[i] != 0) { if (islower(line[i])) { line[i]= toupper(line[i]); } ++i; } printf(“After conversion : %s\n",line); return 0; }

  31. Example 6: Controlling Case of a Character //To convert a string to uppercase #include <stdio.h> #include <ctype.h> int main() { inti=0; char line[]= "my NAME is JOHN"; printf(“Before conversion : %s\n",line); i=0; while (line[i] != 0) { if (islower(line[i])) { line[i]= toupper(line[i]); } ++i; } printf(“After conversion : %s\n",line); return 0; } Before conversion : my NAME is JOHN After conversion : MY NAME IS JOHN

  32. Example 7: Controlling Case of a Character void changeCase1(char *strPtr) { while (*strPtr!= NULL) { if (islower(*strPtr)) *strPtr= toupper(*strPtr); ++strPtr; } } • void changeCase2(char *strPtr) • { • for(;*strPtr!= NULL;strPtr++) • { • if (isupper(*strPtr)) • *strPtr= tolower(*strPtr); • } • } #include <stdio.h> #include <ctype.h> void changeCase1(char *strPtr); void changeCase1(char *strPtr); int main() { char string[] = “my NAME is JOHN"; printf(“Before conversion: %s\n",string); changeCase1(string); printf(“After conversion1: %s\n",string); changeCase2(string); printf(“After conversion2: %s\n",string); return 0; }

  33. Example 7: Controlling Case of a Character void changeCase1(char *strPtr) { while (*strPtr!= NULL) { if (islower(*strPtr)) *strPtr= toupper(*strPtr); ++strPtr; } } • void changeCase2(char *strPtr) • { • for(;*strPtr!= NULL;strPtr++) • { • if (isupper(*strPtr)) • *strPtr= tolower(*strPtr); • } • } #include <stdio.h> #include <ctype.h> void changeCase1(char *strPtr); void changeCase1(char *strPtr); int main() { char string[] = “my NAME is JOHN"; printf(“Before conversion: %s\n",string); changeCase1(string); printf(“After conversion1: %s\n",string); changeCase2(string); printf(“After conversion2: %s\n",string); return 0; } Before conversion : my NAME is JOHN After conversion1 : MY NAME IS JOHN After conversion2 : my name is john

  34. Controlling Case of a Character • Real value does not changed. • The functions only affect characters of letters or alphabets. • does not affect numbers and special characters such as $ and % • If the character is already lowercase or uppercase, the function will not affect the real value • return the original value Example: char cRepeat = ‘Y’; cLetter = strupr(cRepeat); cLetter = ?

  35. Strings Conversion Functions • Conversion functions • In <stdlib.h>(general utilities library) • Convert strings of digits to integer and floating-point values

  36. Strings Comparison Functions • Comparing strings • Computer compares numeric ASCII codes of characters in string intstrcmp( const char *s1, const char *s2 ); • Compares string s1 to s2 • Returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2 intstrncmp(const char *s1, const char *s2, size_t n ); • Compares up to n characters of string s1 to s2 • Returns values as above

  37. ASCII Table ‘A’  65, ‘a’  97

  38. Sample Program 1 #include <stdio.h> #include <string.h> int main() { char acString1[20], acString2[20]; //declaration intiResult; printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); iResult = strcmp( acString1, acString2);//comparing acString1 and acString2 if (iResult > 0 ) printf( "\"%s\" is greater than \"%s\"\n",acString1, acString2 ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\"\n",acString1, acString2 ); else printf( "\"%s\" is less than \"%s\"\n",acString1, acString2 ); return 0; }

  39. Sample Program 1 #include <stdio.h> #include <string.h> int main() { char acString1[20], acString2[20]; //declaration intiResult; printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); iResult = strcmp( acString1, acString2 );//comparing acString1 and acString2 if ( iResult > 0 ) printf( "\"%s\" is greater than \"%s\"\n",acString1, acString2 ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\"\n",acString1, acString2 ); else printf( "\"%s\" is less than \"%s\"\n",acString1, acString2 ); return 0; } Enter two strings: computer programming "computer" is less than "programming" Enter two strings: programming computer "programming" is greater than "computer"

  40. Sample Program 2 #include <stdio.h> #include <string.h> int main() { char acString1[ 20 ], acString2[ 20 ]; intiResult, iCompareCount; printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); printf( "How many characters should be compared: " ); scanf( "%d", &iCompareCount ); iResult = strncmp( acString1, acString2, iCompareCount ); if (iResult > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else printf( "\"%s\" is less than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); return 0; }

  41. Sample Program 2 #include <stdio.h> #include <string.h> int main() { char acString1[ 20 ], acString2[ 20 ]; intiResult, iCompareCount; printf( "Enter two strings: " ); scanf( "%s %s", acString1, acString2 ); printf( "How many characters should be compared: " ); scanf( "%d", &iCompareCount ); iResult = strncmp( acString1, acString2, iCompareCount ); if (iResult > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else if ( iResult == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); else printf( "\"%s\" is less than \"%s\" up to %d characters\n", acString1, acString2, iCompareCount ); return 0; } Enter two strings: computer programming How many characters should be compared: 7 "computer" is less than "programming" up to 7 characters Enter two strings: programming computer How many characters should be compared: 7 "programming" is greater than "computer" up to 7 characters

  42. Built in Functions for String Handling • strcat Appends a string • strchr Finds first occurrence of a given character • strcmp Compares two strings • strcmpi Compares two strings, non-case sensitive • strcpy Copies one string to another • strlen Finds length of a string • strlwr Converts a string to lowercase • strncat Appends n characters of string • strncmp Compares n characters of two strings • strncpy Copies n characters of one string to another • strnset Sets n characters of string to a given character • strrchr Finds last occurrence of given character in string • strrev Reverses string • strset Sets all characters of string to a given character • strspn Finds first substring from given character set in string • strupr Converts string to uppercase

  43. End – Arrays & Strings Q & A!

More Related