Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU.

Similar presentations


Presentation on theme: "Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU."— Presentation transcript:

1 Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU

2 Introduction 2 A string is a sequence of characters that is treated as a single data item. String constant: “String constant example.” “ \”String constant example.\””  \” includes double quote in the string. o printf(“ \”Well Done !\” ”); output: “Well Done !”

3 Declaring and initializing string variables: 3 C does not support strings as a data type. Strings are represent as character arrays. The general form of declaration of a string variable is: char string_name[size]; Example: char city[10]; char name[30]; Size = maximum number of characters in the string plus one (for NULL character ‘\0’)

4 Declaring and initializing string variables: 4 Initialization: Example: 1. char city[18] = “Ahmedabad Gujarat”; 2. char city[18] = {‘A’, ’h’, ‘m’, ‘e’, ‘d’, ‘a’, ‘b’, ‘a’, ‘d’, ‘ ’, ‘G’, ‘u’, ‘j’, ‘a’, ‘r’, ‘a’, ‘t’, ‘\0’ }; 3. char string[]={‘G’, ‘o’, ‘o’, ‘d’, ‘\0’}; size is determine from list of values. 4. char str[10] = “Good”; str Good\0

5 Declaring and initializing string variables: 5 Initialization: Example: 1. char str2[3]=“Good”; //compile time error - size is smaller than specified value 2. char str3[5]; str3=“Good”; we can not separate initialization from declaration. 4. char s1[4]=“abc”; char s2[4]; s2=s1; //Error Array name can not be used as the left operand of an assignment operator.

6 Terminating Null Character 6 The string is a variable-length structure and is stored in a fixed-length array. The array size is not always the size of string and most often it is much larger than the string stored in it. Null character  end-of-string

7 Reading strings from terminal 7

8 Reading strings from terminal  Using scanf function 8 Format specification: %s Example: char name[11]; scanf(“%s”,name); The problem with the scanf function is that it terminates its input on the first white space it finds.

9 Reading strings from terminal  Using scanf function 9 char name[11]; scanf(“%s”,name); Example: Ajay Patel given as input than scanf takes only Ajay as input because blank space (it is white space) is their in it. name Ajay\0??????

10 Reading strings from terminal  Using scanf function 10 Example: char adr1[25],adr2[25]; scanf(“%s%s”,adr1,adr2);

11 Reading strings from terminal  Using scanf function 11 Format specification: %ws scanf(“%ws”,name); Example: char name[10]; scanf(“%5s”,name); The input string RAM will be stored as: name RAM\0?????? 0123456789

12 Reading strings from terminal  Using scanf function 12 Format specification: %ws scanf(“%ws”,name); Example: char name[10]; scanf(“%5s”,name); The input string KRISHNA will be stored as: name KRISH\0???? 0123456789

13 Reading strings from terminal  Using a Line of Text 13 Format specification: %[..]  also known as edit set conversion code. Example, Char line[20]; scanf(“%[^\n]”,line); line AjayPatel \0????????? 012345678910 111213141516171819

14 Reading strings from terminal  Using getchar and gets function 14 Using getchar() function char ch; ch=getchar(); Example next slide

15 Reading strings from terminal  Using getchar and gets function 15 #include void main() { char line[81],ch; int c=0; printf(“Enter text. Press at end.\n”); do { ch=getchar(); line[c]=ch; c++; }while(ch!=‘\n’); c=c-1; line[c]=‘\0’; printf(“line=%s”,line); } Output: Enter texr. Press at end. String is interesting chapter. line=String is interesting chapter.

16 Reading strings from terminal  Using getchar and gets function 16 Using gets() function Header file  stdio.h General format gets(string_variable_name); gets() read characters into string_variable_name from keyboard until a new-line character is encountered and then appends a null character to the string.

17 Reading strings from terminal  Using getchar and gets function 17 Example, char line[81]; gets(line); printf(“%s”,line);

18 Reading strings from terminal  Using getchar and gets function 18 Difference between gets() and scanf() function gets()scanf() Format: gets(string_variable_name ); Format: scanf(“%ws”,name); It can consider white space until new line character encountered. It can not consider white space during reading a string. Example, char ch[10]; gets(ch); Example, char ch[10]; scanf(“%s”,ch); It is used to read line of text. It is not used to read line of text.

19 Writing strings to screen 19

20 Writing strings to screen  using printf() function 20 Format specification: %w.p s Here w – width and p – first p characters of the string. Example char name = “Ajay Patel”; printf(“%s”,name); printf(“%10s”,name); AjayPatel AjayPatel

21 Writing strings to screen  using printf() function 21 char name = “Ajay Patel”; printf(“%5s”,name); printf(“%15.6s”,name); printf(“%-15.6s”,name); AjayPatel AjayP AjayP

22 Writing strings to screen  using printf() function 22 char name = “Ajay Patel”; printf(“%15.0s”,name); 0 characters are printed. So nothing is printed on the screen. printf(“%.3s”,name); printf(“%*.*s”,w,p,string); printf(“%-*.*s”,15,6,name); Aja AjayP

23 Writing strings to screen  using putchar() and puts() function 23 Using putchar() function: char ch=‘A’; putchar(ch); Example, char name[5]=“Ajay”; i=0; while(name[i]!=‘\0’) { putchar(name[i]); i++; } putchar(‘\n’); Ajay\0

24 Writing strings to screen  using putchar() and puts() function 24 Using puts() function: Format: puts(string_variable_name) It prints the string on the screen then move the cursor to the beginning of the next line on the screen. Example, char name[20]; gets(name); puts(name);

25 Arithmetic operations on characters 25 Whenever a character constant or character variable is used in expression, it is automatically converted into an integer value by the system. The integer value depends on the local character set of the system. If the machine ASCII representation, char x=‘a’; printf(“%d\n”,x);  output:- 97 Arithmetic operations can be perform on character constant or character variable. x=‘z’-1;  122(ASCII of z) - 1 = 121

26 Arithmetic operations on characters 26 To check whether the character is upper-case letter or not. ch >= ‘A’ && ch <= ‘Z’ We can convert a character digit to its equivalent integer value using the following relationship. x = character – ‘0’ // Here x is interger. Example, x= ASCII value of ‘7’ - ASCII value of ‘0’ = 55 – 48 = 7

27 Arithmetic operations on characters 27 The C library supports a function that converts a string of digits into their integer values. The function takes the form integer_variable = atoi(string); Example, char number[5] = “2013”; int year; year = atoi(number); atoi() function is stored in the header file stdlib.h.

28 Putting strings together 28 We can not join two strings together by the simple arithmetic addition. Like, string3 = string1 + string2; string2 = string1 + “hello”; are not valid. The characters from string1 and string2 should be copied into the string3 one after the other. The size of array string3 should be large enough to hold the total characters. The process of combining two string together is called concatenation.

29 Comparison of two strings 29 Once again, C does not permit the comparison of two strings directly. Like, if(name1==name2) if(name1==“Ajay”) //are invalid It is therefore necessary to compare the two strings to be tested, character by character.

30 String handling functions 30 Most commonly used string handling functions: FunctionAction strcat()Concatenates two strings strcmp()Compares two strings strcpy()Copies one string over another strlen()Finds the length if a string

31 String handling functions  strcat() function 31 It joins two strings together. It takes the following form: strcat(string1, string2); string2 is appended to string1. Example refer next slide

32 String handling functions  strcat() function 32 Example char name[15] = “Ajay ”; char sname[6] = “Patel”; strcat(name,sname); name Ajay\0 sname Patel \0 name AjayPatel \0

33 String handling functions  strcat() function 33 Example char name[15] = “Ajay ”; strcat(name,”Patel”); name Ajay\0 name AjayPatel \0

34 String handling functions  strcat() function 34 Example char name[15]; char fname[6]=“Ajay ”,lname[6]=“Patel”; strcat(strcat(name,fname),lname); fname Ajay\0 name AjayPatel \0 lname Patel \0

35 String handling functions  strcmp() function 35 It compares two strings and has a value 0 if they are equal. If they are not, it has numeric difference between the first non- matching characters in the strings. It takes the following form: strcmp(string1, string2); Example refer next slide

36 String handling functions  strcmp() function 36 Example strcmp(“their”,”there”); It returns a value -9 (Ascii of (i) - Ascii of (r) ).

37 String handling functions  strcmp() function 37 Example char name1[15]=“Ajay”; char name2[15]=“Ajay”; int x; x = strcmp(name1,name2); if(x != 0) {printf(“strings are not equal. ”); } else { printf(“strings are equal. ”); }

38 String handling functions  strcpy() function 38 It copies one string over another. It takes the following form: strcpy(string1, string2); it assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. Example, strcpy(city,”AHMEDABAD”); strcpy(city1,city2); size of the array city1 should be large enough to receive the contents of city2.

39 String handling functions  strlen() function 39 It counts and returns the number of characters in a string. The general form of strlen is: n = strlen(string); Where n is an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character. Example char city[15]=“Ahmedabad”; int n=strlen(city);  n=9 int x=strlen(“Baroda Gujarat”);  x=14

40 Other String handling functions  strncpy() function 40 The header file string.h contains many more string manipulation functions. It copies only left-most n characters of the source string to the target string variable. strncpy(s1,s2,5); This statement copies the first 5 characters of the source string s2 into the target string s1. Since the first 5 characters may not include the terminating null character, we have to place it explicitly in the 6 th position of s2 as shown below: s1[6]=‘\0’;

41 Other String handling functions  strncpy() function 41 Example, char str1=“Nirma Uni”; char str2=“IDS”; strncpy(str1,str2,2);  IDrma Uni

42 Other String handling functions  strncmp() function 42 The general form is: strncmp(s1,s2,n); this compares the left-most n characters of s1 and s2 and returns 0 if they are equal. Negative number, if s1 sub-string is less than s2 Positive number, otherwise.

43 Other String handling functions  strncat() function 43 The general form is: strncmp(s1,s2,n); This call will concatenate the left-most n characters of s2 to the end of s1. After strncat(s1,s2,4); excution: S1:BALA\0 S2:GURUSAMY\0 S1:BALAGURU\0

44 Other String handling functions  strstr() function 44 It is a two-parameter function that can be used to locate sub-string in a string. This takes the forms: strstr(s1,s2); strstr(s1,”ABC”); The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer.

45 Other String handling functions  strstr() function 45 Example, char s1[15]=“Nirma University”, s2[10]=“Uni”; if(strstr(s1,s2)==NULL) printf(“substring is not found.”); else printf(“s2 is as substring of s1.”);

46 Other String handling functions  strchr() function 46 We also have functions to determine the existence of a character in a string. The function strchr(s1,’m’); will locate the first occurrence of the character ‘m’. The function strrchr(s1,’m’); will locate the last occurrence of the character ‘m’ in the string s1.

47 Table of strings 47 A list of names can be treated as a table of string and a two-dimensional character array can be used to store the entire list. Example, char student[30][20]; It is used store 30 student names each of length not more than 20 characters.

48 Write a C program to copy one string into another without using string handling function. 48 #include void main() { char str1[50],str2[20]; int i; clrscr(); printf(“Enter the string2:”); gets(str2); for(i=0;str2[i]!=‘\0’;i++) str1[i]=str2[i]; str1[i]=‘\0’; printf(“String1 = %s”,str1); getch(); } Output : Enter the string2: Nirma University String1 = Nirma University

49 Write a C program to compare two strings without using string handling function. 49 #include void main() { char str1[50],str2[20]; int i; clrscr(); printf(“Enter the string1 and string2:”); gets(str1); gets(str2); i=0; while(str1[i]==str2[i] && str1[i]!=‘\0’ && str2[i]!=‘\0’) i++; if(str1[i]==‘\0’ && str2[i]==‘\0’) printf(“Strings are equal.”); else printf(“Strings are not equal.”); getch(); }

50 Write a C program that counts the number of words from the given string #include void main() { char str[100]; int count=1,i=0; clrscr(); printf("Enter the string:"); gets(str); while(str[i]!='\0') { if(str[i]==' ') { count++; } i++; } printf("\nNo. of words in string are: %d",count); getch(); } 50

51 Write a program to print following using for loop: 51

52 52 #include void main() { char str[20]; int i,j; clrscr(); printf("Enter the string:"); scanf("%s",str); for(i=0;i<strlen(str);i++) { for(j=0;j<=i;j++) printf("%c",str[j]); printf("\n"); } getch(); }

53 Thank You


Download ppt "Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU."

Similar presentations


Ads by Google