Presentation is loading. Please wait.

Presentation is loading. Please wait.

Problem Solving and Program Design in C Chap. 8 Strings Chow-Sing Lin.

Similar presentations


Presentation on theme: "Problem Solving and Program Design in C Chap. 8 Strings Chow-Sing Lin."— Presentation transcript:

1 Problem Solving and Program Design in C Chap. 8 Strings Chow-Sing Lin

2 CSIE@NUTN String Basics String - a data structure which is a grouping of characters Calls to scanf or printf used a string constant as the first argument. printf("Average = %.2f",avg); A string of 14 characters. The blank in the string are characters just as valid as those requiring ink! Dr. Chow-Sing LinStrings - CH92

3 CSIE@NUTN Declaring and Initializing String Variables A string in C is implemented as an array, so declaring a string variable is the same as declaring an array of type char. In char str[20] = "Initial value" ; str in memory after this declaration with initialization – ‘\0’  null character that marks the end of a string. Dr. Chow-Sing LinStrings - CH93 Initialvalue\0?????? [0][4][9] [14] [19]

4 CSIE@NUTN Arrays of Strings An array of strings is a two-dimensional array of characters in which each row is one string – The following are statements to declare an array to store up to 30 names. Each of which is less than 25 characters long. Dr. Chow-Sing LinStrings - CH94 #define NUM_PEOPLE 30 #define NAME_LEN 25 char names[NUM_PEOPLE][NAME_LEN];

5 CSIE@NUTN Arrays of Strings (cont.) Initialize an array of strings at declaration in the following manner Dr. Chow-Sing LinStrings - CH95 char month[12][10] = {“January”, ”February”, ”March”, ”April”, ”May”,”June”, ”July”, ”August”, ”September”, ”October”, ”November”, ”December”} ;

6 CSIE@NUTN Input / Output with printf and scanf printf and scanf can handle string arguments as long as the placeholder %s is used in the format string printf(“Topic: %s\n”, string_var); – %s placeholder in a printf format string can be used with a minimum field with as shown printf(“***%8s***%3s***\n”, ”Short”, ”Strings”); – Left-justified printf(“%-20s\n”, president); Dr. Chow-Sing LinStrings - CH96

7 CSIE@NUTN Figure 9.1 Right and Left Justification of Strings Dr. Chow-Sing LinStrings - CH97

8 CSIE@NUTN Input / Output with printf and scanf Dr. Chow-Sing LinStrings - CH98

9 CSIE@NUTN Execution of scanf(“%s”,dept); scanf () skips leading whitespace characters such as blanks, newline, and tabs. Dr. Chow-Sing LinStrings - CH99

10 CSIE@NUTN Invalid input format Function scanf would have difficulty, if – some essential whitespace between values were omitted – a non-whitespace separator were substituted For example If the data were entered as > MATH1270 TR 1800 – scanf would store the eight-character string “MATH1270” Dr. Chow-Sing LinStrings - CH910

11 CSIE@NUTN Invalid Input Format (cont.) For example > MATH,1270,TR,1800 scanf function would store the entire 17-character string plus ‘\0’ – Example 8.1 Dr. Chow-Sing LinStrings - CH911

12 CSIE@NUTN String Library Functions : Assignment and Substrings Accustomed to using the assignment operator = to copy data into a variable – Not working for string assignment! The array address is constant and cannot be changed through assignment char one_str[20]; one_str =“test string” ; /* does not work*/ Some String Library Functions from string.h – Page 481-- Table 8.1 – Appendix B-13 Dr. Chow-Sing LinStrings - CH912

13 CSIE@NUTN String Assignment Function strcpy copies the string that is its second argument into its first argument strcpy(one_str, “test string”) ; /* ok */ strcpy(one_str, ”a very long test string”); – Overflow one_str, storing the final characters ‘i’, ‘n’, ‘g’, and ‘\0’ in memory allocated for other variables. Dr. Chow-Sing LinStrings - CH913

14 CSIE@NUTN String Assignment (cont.) The string library provides another string- copying function named strncpy – An argument specifying the number of characters to copy(call this number n) strncpy(one_str, “Test String”, 20); The same as the call strcpy(one_str, ”Test String”); Dr. Chow-Sing LinStrings - CH914 TestString\O [0][4][9][14][19]

15 CSIE@NUTN String Assignment (cont.) The string library provides another string-copying function named strncpy strncpy(one_str, ”A very long test string”, 20); – This is not a valid string in one_str array!! – One can assign as much as will fit of a source string(source) to a destination(dest) of length dest_len by using these two statements strncpy(dest, source, dest_len -1) ; dest[dest_len-1]=‘\0’ ; Dr. Chow-Sing LinStrings - CH915 Averylongteststr [0][4][9][14][19]

16 CSIE@NUTN Substrings The data areas of strncpy and the calling function just before the return from the call to strncpy in this code fragment char result[10], s1[15]=“Jan. 30, 1996”; strncpy(result,s1,9); result[9]=‘\0’; Dr. Chow-Sing LinStrings - CH916

17 CSIE@NUTN Substrings(cont’) The array reference with no subscript actually represents the address of the initial array element. The code fragment would extract the substring “30” char result[10], s1[15]=“Jan. 30, 1996”; strncpy(result,&s1[5],2); result[2]=‘\0’; Dr. Chow-Sing LinStrings - CH917

18 CSIE@NUTN Examples Example 8.2 (page 484) Example 8.3 (how? Interesting …) Dr. Chow-Sing LinStrings - CH918

19 CSIE@NUTN Longer Strings : Concatenation Concatenation – String library function strcat and strncat modify their first string argument by adding all or part of their second string argument at the end of the first argument. – Book Page 489 example 8.4 Dr. Chow-Sing LinStrings - CH919

20 CSIE@NUTN Strlen strlen(s1)  8 strlen(strcat(s1,s2))  16 Dr. Chow-Sing LinStrings - CH920 #define STRSIZ 20 char s1[STRSIZ] = “Jupiter “, s2[STRSIZ] = “Symphony” ; printf(“%d %d\n”, strlen(s1), strlen(strcat(s1,s2))) ; printf(“%s\n”,s1);

21 CSIE@NUTN strlen (cont’) The condition correctly verifies that the sum of the length of s1 and s2 is strictly less than STRSIZ. Dr. Chow-Sing LinStrings - CH921 If (strlen(s1) + strlen(s2) < STRSIZ) strcat(s1,s2) ; else { strncat(s1, s2, STRSIZ – strlen(s1) – 1) ; s1[STRSIZ-1] = ‘\0’; }

22 CSIE@NUTN Distinction Between Characters and Strings ‘Q’ and “Q” are different !! Dr. Chow-Sing LinStrings - CH922 Q Q\0??????… Character ‘Q’ String “Q” (represented by its initial address)

23 CSIE@NUTN Scanning a Full Line scanf() and fscanf() are not suitable for scanning a full line for treating blanks as delimiters. – Use gets() or fgets() char line[80]; printf(“Type in a line of data. \n >”); gets(line); Dr. Chow-Sing LinStrings - CH923

24 CSIE@NUTN Scanning a Full Line(cont.) If the user responds to the prompt as follows by gets Type in a line of data. > Here is a short sentence. – The value stored in line[] would be Here is a short sentence. \0 – The ‘\n’ character representing the or key pressed at the end of the sentence is not stored. – gets can overflow its string argument if the user enters a longer data line than will fit. Dr. Chow-Sing LinStrings - CH924

25 CSIE@NUTN Scanning a Full Line (cont.) Function fgets() will never store more than n-1 characters from the data file, and the final character stored will always be ‘\0’ – If fgets() has room to store the entire line of data, it will include ‘\n’ before ‘\0’. – If the line is truncated, no ‘\n’ is stored. When a call to fgets encounters the end of file, the value returned is the address 0, which is considered the null pointer. Dr. Chow-Sing LinStrings - CH925

26 CSIE@NUTN Figure 8.8 Demonstration of Whole- Line Input Dr. Chow-Sing LinStrings - CH926

27 CSIE@NUTN Figure 9.8 Demonstration of Whole- Line Input Dr. Chow-Sing LinStrings - CH927

28 CSIE@NUTN Exercises for section 8.3 Give the string pres(value is “Adams, John Quincy”) and the 40 character temporary variables tmp1 and tmp2, what string is displayed by the following code fragment? Dr. Chow-Sing LinStrings - CH928 strncpy(tmp1,&pres[7],4); tmp1[4]=‘\0'; strcat(tmp1," "); strncpy(tmp2,pres, 5); tmp2[5]=‘\0'; printf("%s\n",strcat(tmp1,tmp2)); John Adams Answer

29 CSIE@NUTN String Comparison If the first n characters of str1 and str2 match and str1[n],str2[n] are the first non-matching corresponding characters, str1 is less than str2 if str1[n] < str2[n] str1 t h r i l l str1 e n e r g y str2 t h r o w str2 f o r c e First 3 letters match First 0 letters match str1[3] < str2[3] str1[0] < str2[0] ‘i‘ < ‘o’ ‘e‘ < ‘f’ str1 < str2 Dr. Chow-Sing LinStrings - CH929

30 CSIE@NUTN String Comparison(cont.) If str1 is shorter than str2 and all the characters of str1 match the corresponding characters of str2, str1 is less than str2 str1 j o y str2 j o y o u s Dr. Chow-Sing LinStrings - CH930

31 CSIE@NUTN String Comparison(cont.) Dr. Chow-Sing LinStrings - CH931 Possible Results of strcmp(str1, str2) RelationshipValue ReturnedExample str1 is less then str2negative integerstr1 is “marigold” str2 is “tulip” str1 equals str2zerostr1 and str2 are both “end” str1 is greater than str2positive integerstr1 is “shrimp” str2 is “crab”

32 CSIE@NUTN Example 8.5 When alphabetizing a list, string comparisons are essential. – Use selection sort. – Compares the numeric and string versions of code that compares list elements in the search for the index of smallest. Dr. Chow-Sing LinStrings - CH932

33 CSIE@NUTN EXAMPLE 8.6 Dr. Chow-Sing LinStrings - CH933 When we process a list of string data interactively, we often do not know in advance how much data will be entered. Use a sentinel-controlled loop to prompt the user to type in the sentinel value when entry of the data is complete.

34 CSIE@NUTN Exercises for Section 8.4 Write a message indicating whether name1 and name2 match Dr. Chow-Sing LinStrings - CH934 if(strcmp(name1, name2)==0) printf(“Names match. \n”); else printf(“Names do not match. \n”); Answer

35 CSIE@NUTN Exercises for section 8.4(cont.) Store in the string variable word the value either of w1 or of w2. Choose the value that comes first alphabetically. Dr. Chow-Sing LinStrings - CH935 if (strcmp(w1, w2)< 0) strcpy(word, w1); else strcpy(word, w2); Answer

36 CSIE@NUTN Arrays of pointers Let’s look closely at the code that exchanges two strings Dr. Chow-Sing LinStrings - CH936

37 CSIE@NUTN Arrays of pointers(cont.) Copy strings between memory cells. – BAD !! Dr. Chow-Sing LinStrings - CH937

38 CSIE@NUTN Arrays of pointers(cont.) C’s use of pointers to represent arrays presents us with an opportunity to develop an alternate approach to our sorting problem char *alpha[5]; Dr. Chow-Sing LinStrings - CH938

39 CSIE@NUTN Example 8.7 The Open School admits children to its kindergarten in the order in which they apply Most of the staff’s use of the list of applicants is made easier if the list is alphabetized How the order of string exchanged in select_sort_str() ?? – Only the pointers are exchanged!! (page. 499) Dr. Chow-Sing LinStrings - CH939

40 CSIE@NUTN Example9.7(cont.) Dr. Chow-Sing LinStrings - CH940

41 CSIE@NUTN Example9.7(cont.) Dr. Chow-Sing LinStrings - CH941

42 CSIE@NUTN Example9.7(cont.) Dr. Chow-Sing LinStrings - CH942 Only the pointers of strings are exchanged !!

43 CSIE@NUTN Arrays of string constants Two alternative for representing the list of month Dr. Chow-Sing LinStrings - CH943 char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” }; char *month[12] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” };

44 CSIE@NUTN Character Operations Character Input/output – getchar() It is used to get the next character from the standard input source getchar does not expect the calling module to pass as an argument the address of a variable in which to store the input character. Either of the following two expressions can be used to store the next available input character in ch. scanf(“%c”, &ch) ch = getchar() getc(inp) -- get a char from a file. Dr. Chow-Sing LinStrings - CH944

45 CSIE@NUTN Example 8.8 Write a scanline function that use getchar Dr. Chow-Sing LinStrings - CH945

46 CSIE@NUTN Char output The standard library’s single-character output facilitate are putchar (for display on the standard output device) and putc (for files). putchar(‘a’) ; putc(‘a’, outp); Dr. Chow-Sing LinStrings - CH946

47 CSIE@NUTN Character analysis and conversion We need to know if a character belongs to a particular subset of the overall character set. The library #include as defines facilities for answering questions like these and also provides routines to do common character conversions like uppercase to lowercase or lowercase to uppercase. Dr. Chow-Sing LinStrings - CH947

48 CSIE@NUTN Character analysis and conversion(cont.) FactilityChecksExample isalphaif argument is a letter of the alphabet if(isalpha(ch)) printf(“%c is a letter \n”, ch); isdigitif argument is one of the ten decimal digits dec_digit = isdigit(ch); islower (isupper) if argument is a lowercase (or uppercase) letter of the alphabet if (islower(fst_let)){ print(“\n Error: sentence”); printf(“should begin with a”); printf(“capital letter. \n”);} ispunctif argument is a punctuation character, that is, a noncontrol character that is not a spacem a letter of the alphabet, or a digit if(ispunct (ch)) printf(“Punctuation mark: %c \n”,ch); isspaceif argument is a whitespace character such as a space, a newline, or a tab c = gether(); While (isspace(c) && c != EOF) c = gether(); Dr. Chow-Sing LinStrings - CH948

49 CSIE@NUTN Character analysis and conversion(cont.) FactilityChecksExample tolower (toupper) its lowercase(or uppercase) letter argument to the uppercase(or lowercase) equivalent and returns this equivalent as the value of the call If (islower(ch)) printf(“Capital %c = %c \n”,ch, toupper(ch)); Dr. Chow-Sing LinStrings - CH949

50 CSIE@NUTN Example 8.9 A function string_greater that could be used to find out-of-order elements when alphabetizing a list of strings in a situation in which the case of the letters should be ignored. Dr. Chow-Sing LinStrings - CH950

51 CSIE@NUTN Example 8.9(cont.) Dr. Chow-Sing LinStrings - CH951

52 CSIE@NUTN String-to-Number and Number-to-String Conversions Review of user of scanf Dr. Chow-Sing LinStrings - CH952 DeclarationStatement Data ( means blank) Value Stored char tscanf(“%c”, &t); g \n A \n A int nscanf(“%d”, &n); 32 -8.6 +19 32 -8 19 double xscanf(“%lf”, &x); 4.32 -8 1.76e-3 4.32 -8.0.00176 char str [10]scanf(“%s” str); hello \n overlengthy hello\0 overlengthy\0 (overruns length of str)

53 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) Placeholders used with printf Dr. Chow-Sing LinStrings - CH953 ValuePlaceholderOutput ( means blank) ‘a’%c %3c %-3C a a a -10%d %2d %4d %-5d -10 -10

54 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) Placeholders used with printf (Cont.) Dr. Chow-Sing LinStrings - CH954 ValuePlaceholderOutput ( means blank) 49.76%.3f %.1f %10.2f %10.3e 49.760 49.8 49.76 4.976e+01 “fantastic”%s %6s %12s %-12s %3.3s fantastic fantastic fantastic fantastic fan

55 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) The stdio library gives us this ability through similar function – sprintf() – sscanf() The sprintf function requires space for a string as its first argument Dr. Chow-Sing LinStrings - CH955

56 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) Consider this call to sprintf – Assume that s has been declared as char s[100] – The value of type int variables mon, day, and year Dr. Chow-Sing LinStrings - CH956 8 8 23 1914 mon day year sprintf(s, “%d/%d/%d”, mon, day, year);

57 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) Function sprintf substitutes values for placeholders just as printf does sprintf stores it in the character array accessed by its initial argument Dr. Chow-Sing LinStrings - CH957 8 / 2 3 / 1 9 1 4 \ 0 s

58 CSIE@NUTN String-to-Number and Number-to-String Conversions (Cont.) example – the illustration that follows shows how stores values from the first string Dr. Chow-Sing LinStrings - CH958 sscanf(“ 85 96.2 hello”, “%d%1f%s”, &num, &val, word); 85 96.2 h e l l o \0 num val word

59 CSIE@NUTN Example 8.11 The conversion of DATE to three numbers (12 January 1941  1 12 1941) and reverse conversion. Dr. Chow-Sing LinStrings - CH959

60 CSIE@NUTN 1-60 Figure 8.18 Functions That Convert Representations of Dates

61 CSIE@NUTN 1-61 Figure 8.18 Functions That Convert Representations of Dates (cont’d)

62 CSIE@NUTN 1-62 Figure 8.18 Functions That Convert Representations of Dates (cont’d)

63 CSIE@NUTN 1-63 Figure 8.18 Functions That Convert Representations of Dates (cont’d)

64 CSIE@NUTN String Processing Illustrated Case Study – Text Editor – Problem Design and implement a program to perform editing operations on a line of text editor should be able to – locate a specified target substring – delete a substring – insert a substring at a specified location editor should expect source strings of less than 80 characters Dr. Chow-Sing LinStrings - CH964

65 CSIE@NUTN Case Study (Cont.) Dr. Chow-Sing LinStrings - CH965

66 CSIE@NUTN Case Study (Cont.) Dr. Chow-Sing LinStrings - CH966

67 CSIE@NUTN Case Study (Cont.) Dr. Chow-Sing LinStrings - CH967

68 CSIE@NUTN Dr. Chow-Sing LinStrings - CH968

69 CSIE@NUTN Dr. Chow-Sing LinStrings - CH969

70 CSIE@NUTN Dr. Chow-Sing LinStrings - CH970

71 CSIE@NUTN Dr. Chow-Sing LinStrings - CH971

72 CSIE@NUTN Dr. Chow-Sing LinStrings - CH972 Figure 8.21 Sample Run of Text Editor Program

73 CSIE@NUTN Common Programming Error When we work with numeric values or single characters – we commonly compute a value of interest in a function – storing the result value temporarily in a local variable of the function – until it is returned to the calling module using the return statement – But such functions do not actually return a string value Dr. Chow-Sing LinStrings - CH973

74 CSIE@NUTN Common Programming Error (Cont.) The function’s data area is deallocated as soon as the return statement is executed – it is not valid to access from the calling module the string the function constructed in its own variable Figure 8.22 shows a poor rewrite of the scanline function from Fig. 8.15 Dr. Chow-Sing LinStrings - CH974

75 CSIE@NUTN Dr. Chow-Sing LinStrings - CH975 Figure 8.15 Implementation of scanline Function Using getchar

76 CSIE@NUTN Dr. Chow-Sing LinStrings - CH976 Figure 8.22 Flawed scanline Returns Address of Deallocated Space

77 CSIE@NUTN Common Programming Error (Cont.) String use is the overflow of character arrays allocated for strings Whatever was stored in the cells following array dept has just been overwritten !! – If memory was being used for other program variables, values will appear to change spontaneously Dr. Chow-Sing LinStrings - CH977 MATH,1270,TR,1800\0 [0] [4] [9] space not allocated for dept Execution of scanf(“%s%d%s%d”, dept, &course_num, days, &time); on Entry of Invalid Data


Download ppt "Problem Solving and Program Design in C Chap. 8 Strings Chow-Sing Lin."

Similar presentations


Ads by Google