Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Strings Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.

Similar presentations


Presentation on theme: "Chapter 9 Strings Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪."— Presentation transcript:

1 Chapter 9 Strings Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. E-mail : comjyh@ccu.edu.tw TA: 鄭筱親 陳昱豪

2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 本章重點 Null-terminated char array –Consecutive characters, ended with ‘\0’ Array of string: Array of array? array of pointer ? 指標的加法與減法, 比較 : Appendix D 工作站上控制游標, 以及單鍵輸入 (curses library)

3 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-3 Outline 9.1 STRING BASICS 9.2 STRING LIBRARY FUNCTIONS:ASSIGNMENT AND SUBSTRINGS 9.3 LONGER STRINGS:CONCATENATION AND WHOLE- LINE INPUT 9.4 STRING COMPARISON 9.5 ARRAYS OF POINTERS 9.6 CHARACTER OPERATIONS 9.7 STRING-TO-NUMBER AND NUMBER-TO STRING CONVERSIONS 9.8 STRING PROCESSING ILLUSTRATED –CASE STUDY: TEXT EDITOR 9.9 COMMON PROGRAMMING ERRORS

4 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-4 9.1 STRING BASICS Declaring and initializing string variables –A string in C is implemented as a char array –Null character Character ‘\0’ that marks the end of a string in C –For example char str[20] = “Initial value”; A string constant can be associated with a symbolic name using the #define directive Initialvalue\0?????? [0][0][4][9][14][19]

5 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-5 ARRAYS OF STRINGS An array of strings can be defined as a two- dimensional array of characters in which each row is one string. For example –#define NUM_PEOPLE 30 –#define NAME_LEN 25 –char names [NUM_PEOPLE][NAME_LEN]; –char month[12][10] = { “enero”, “febrero”, “marzo”, “abril”, “mayo”, “junio”, “julio”, “agosto”, “septiembre”, “octubre”, “noviembre”, “diciembre”};

6 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-6 OUTPUT WITH printf printf(“Topic: %s\n”, string_var); printf(“***%8s***%3s***\n”, “Short”, “Strings”); –The first string is displayed right-justified in a field of eight columns. –The second string is longer than the specified field width, so the field is expanded to accommodate it exactly with no padding. printf(“%-20s\n”, president); –Placing a minus sign prefix on a placeholder’s field width causes left justification of the value displayed.

7 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-7 INPUT WITH scanf( ) char dept[STRING_LEN]; scanf(“%s”, dept); –Array output arguments are always passed to functions by sending the address of the initial array element –scanf(“%s”, ) skips leading whitespace characters such as blanks, newlines, and tabs –When it comes across a whitespace character, scanning stops

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-8 Figure 9.2 String Input/Output with scanf and printf

9 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-9 Figure 9.3 Execution of scanf ("%s", dept);

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-10 Figure 9.4 Execution of scanf("%s%d%s%d", dept, &course_num, days, &time); on Entry of Invalid Data

11 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-11 9.2 STRING LIBRARY FUNCTIONS:ASSIGNMENT AND SUBSTRINGS Array name with no subscript represents the address of the initial array element char one_str[20]; one_str = “Test string”; /* Does not work */ Function strcpy copies the string that is its second argument into its first argument. The return value of most string functions is char *, the returned string

12 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-12 String Library Functions: Assignment and Substrings (cont’d) Function strncpy takes an argument specifying the number of characters to copy. For example: strncpy(one_str, "Test string", 20); would give one_str the value:

13 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-13 Substrings A fragment of a longer string For example –Assuming the prototype of strncpy is char *strncpy (char *dest, const char *source, size_t n); –The code fragment char result[10], sl[15] = “Jan. 30, 1996”; strncpy (result, sl, 9); result[9] = ‘\0’;

14 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-14 Figure 9.5 Execution of strncpy(result, s1, 9); result[9] = ‘\0’;

15 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-15 Figure 9.6 Execution of strncpy(result, &s1[5], 2);

16 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-16 EXAMPLE 9.3 (Example 9.2 自己看 & 試試, 擷取切割子字串 ) –strtok() The program in Fig. 9.7 breaks compounds into their elemental components, assuming that each element name begins with a capital letter and that our implementation is using the ASCII character set.

17 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-17 string length- in a character array, the number of characters before the first null character –As found by strlen( ) –The type of the value returned is size_t, an unsigned integer type empty string- a string of length zero

18 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-18 Figure 9.7 Program Using strncpy and strcpy Functions to Separate Compounds into Elemental Components Na2S2O3 硫代硫酸鈉 NaCl H2SO4 H2O

19 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-19 9.3 LONGER STRINGS:CONCATENATION AND WHOLE-LINE INPUT Concatenation –Joining of two strings –String library functions 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. –The strncat() function appends not more than “third argument” characters from “second argument”, and then adds a terminating `\0'. 跟 strncpy 不太一樣

20 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-20 Distinction Between Characters and Strings Note the difference internally between the representations of the character 'Q' and the string "Q". If you wish to add a single character at the end, you should view the string as an array and assign to the end, including the null character

21 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-21 Scanning a Full Line gets –Interactive input of one complete line of data Consider this code fragment: char line[80]; printf("Type in a line of data.\n> "); gets(line); The value stored in line would be The \n character representing the or key pressed at the end of the sentence is not stored when using gets( ).

22 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-22 SCANNING A FULL LINE fgets –Takes three arguments Output parameter string Maximum number of characters to store (n) –Never store more than n-1 characters –Final character stored will always be ‘\0’ File pointer to the data source –If it has room to store entire line, it will include ‘\n’ before ‘\0’, which is different from gets( ) –Return 0 means it encounters the end of file –gets( ) is unsafe. Some compilers will warn you

23 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-23 Figure 9.8 Demonstration of Whole-Line Input 自己看 …

24 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-24 Figure 9.8 Demonstration of Whole-Line Input

25 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-25 9.4 STRING COMPARISON str1 < str2 ?? No! The standard string library provides the int function strcmp for comparison of two strings. strcmp seperates its argument pairs into three categories. RelationshipValue returnedExample str1 is less than 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” TABLE 9.2 Possible Results of strcmp(str1,str2)

26 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-26 String Comparison

27 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-27 EXAMPLE 9.5 String comparisons are essential when alphabetizing a list. To alphabetize a list of words made up of either all uppercase or all lowercase letters, we could use the selection sort algorithm. Figure 9.9 compares the numeric and string versions of code that compares list elements in the search for the index of the smallest. It also shows the numeric and string versions of a code fragment that exchanges two array elements.

28 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-28 Figure 9.9 Numeric and String Versions of Portions of Selection Sort That Compare and Exchange Elements Any better codes? Fig 08.17

29 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-29 Figure 9.11 Exchanging String Elements of an Array 9.5 ARRAYS OF POINTERS

30 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-30 Figure 9.12 Executing strcpy (list [index_of_min], list[fill]); String is an array of chars C represents every array by its starting address –list[0], …, list[4] are addresses 換一種想法與作法 –Array of pointers

31 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-31 char *alphap[5] Is just as legitimate an argument as original[i] Using array of pointers represent an ordering –Pointer requires less space than a whole string –Executes faster –Spelling correction made in original will affect all Figure 9.13 An Array of Pointers alphap[?] 跟 original[?]

32 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-32 EXAMPLE 9.7 The Open School admits children to its kindergarten in the order in which they apply. However, most of the staff’s use of applicants is made easier if the list is alphabetized. The program in Fig.9.14 takes an input list of names reflecting the order in which applications were received and creates an array of pointers through which the list can be accessed in alphabetical order.

33 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-33 Figure 9.14 Two Orderings of One List Using an Array of Pointers

34 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-34 Figure 9.14 Two Orderings of One List Using an Array of Pointers (cont’d)

35 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-35 Figure 9.14 Two Orderings of One List Using an Array of Pointers (cont’d) 要來玩玩 qsort( ) 嗎 ? (Review of function pointers)

36 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-36 ARRAYS OF STRING CONSTANTS C permits the use of an array of pointers to present a list of string constants. For example –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”}; – 指標與陣列的曖昧關係 …

37 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-37 9.6 CHARACTER OPERATIONS C provides character input/output routines as part of the stdio library. An extensive collection of facilities for character analysis and conversion is available in the library we #include as int getchar ( ) –Get the next character from the standard input source –Take no arguments and return the character as its result –Return EOF if encounter the end of file int getc (FILE *inp) –Get a single character from a file –The character returned is obtained from the file accessed by file pointer inp putchar( ) & putc( ) for char output 類似 scanf(“%c”,&ch)

38 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-38 EXAMPLE 9.8 In fig. 9.15 a scanline function uses getchar. scanline function –Take as its first argument the string variable in which to store the input line –Take a second argument indicating the amount of space available –Store in the output argument either the full input line or as much as will fit

39 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-39 Figure 9.15 Implementation of scanline Function Using getchar

40 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-40 CHARACTER ANALYSIS AND CONVERSION FacilityChecksExample 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)){ printf(“\nError: sentence”); printf(“should begin with a”); printf(“capital letter.\n”) } ispunctIf argument is a punctuation character If(ispunct(ch)) printf(“Punctuation mark: %c\n”, ch) isspaceIf argument is a whitespace character c=getchar(); while(isspace(c) && c!=EOF) c=getchar();

41 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-41 TABLE 9.3 Character Classification and Conversion Facilities in ctype Library FacilityConvertsExample 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))

42 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-42 EXAMPLE 9.9 ( 自行參閱, 自修 ) Figure 9.16 shows 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.

43 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-43 Figure 9.16 String Function for a Greater- Than Operator That Ignores Case

44 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-44 Figure 9.16 String Function for a Greater- Than Operator That Ignores Case (cont’d)

45 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-45 9.7 STRING-TO-NUMBER AND NUMBER- TO STRING CONVERSIONS sprintf –Require space for a string as its first argument –Substitute values for placeholders, instead of printing the result, sprintf stores it in the character array accessed by its initial argument sscanf –Take data from the string that is its first argument

46 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-46 Review of Use of scanf

47 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-47 Placeholders Used with printf %3.3s Min width Max width

48 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-48 Figure 9.18 Functions That Convert Representations of Dates ( 直接看程式 )

49 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-49 Figure 9.18 Functions That Convert Representations of Dates (cont’d)

50 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-50 Figure 9.18 Functions That Convert Representations of Dates (cont’d)

51 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-51 Figure 9.18 Functions That Convert Representations of Dates (cont’d)

52 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-52 9.8 STRING PROCESSING ILLUSTRATED CASE STUDY:TEXT EDITOR(1/5) ( 自修 ) Step 1: Problem –Design and implement a program to perform editing operations on a line of text. –Your editor should be able to locate a specified target substring, delete a substring, and insert a substring at a specified location. –The editor should expect source strings of less than 80 characters.

53 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-53 CASE STUDY:TEXT EDITOR(2/5) Step 2: Analysis –Problem Constant MAX_LEN 100 –Problem Inputs char source [MAX_LEN] char command –Problem Outputs char source [MAX_LEN]

54 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-54 CASE STUDY:TEXT EDITOR(3/5) Step 3: Design –Initial Algorithm 1. Scan the string to be edited into source 2. Get an edit command 3. While command isn’t Q 4. Perform edit operation 5. Get an edit command –Refinement And Program Structure Local Variables char str[MAX_LEN] int index

55 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-55 CASE STUDY:TEXT EDITOR(4/5) Step 3: Design –Algorithm For Do_Edit 1.switch command ‘D’ : 2. Get the substring to be deleted (str) 3. Find the position of str in source 4. if str is found, delete it ‘I’ :5. Get the substring to insert (str) 6. Get position of insertion (index) 7. Perform insertion of str at index position of source ‘F’8. Get the substring to search for (str) 9. Find the position of str in source 10. Report position otherwise: 11. Display error message

56 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-56 Figure 9.19 Structure Chart for Text Editor Program

57 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-57 CASE STUDY:TEXT EDITOR(5/5) Step 4: Implementation (Figure 9.20 、 Figure 9.21) Step 5: Testing

58 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-58 Figure 9.20 Text Editor Program ( 自修 )

59 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-59 Figure 9.20 Text Editor Program (cont’d)

60 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-60 Figure 9.20 Text Editor Program (cont’d)

61 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-61 Figure 9.20 Text Editor Program (cont’d)

62 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-62 Figure 9.20 Text Editor Program (cont’d)

63 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-63 Figure 9.20 Text Editor Program (cont’d)

64 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-64 Figure 9.21 Sample Run of Text Editor Program

65 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-65 9.9 COMMON PROGRAMMING ERRORS Figure 9.22 shows a poor rewrite of scanline function from Fig.9.15.Figure 9.22 –Lifetime (comparing to scope) An error that creeps into C programs with string use is the misuse or neglect of the & operator – 請記得, string 就是 array of chars, array 的名字就是 0 元素 的位置 Another problem that is common with string use is the overflow of character arrays allocated for strings. All strings end with the null character, ‘\0’ 字串的比較跟指定, 請用 strcmp( ) 跟 strcpy( )

66 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-66 Figure 9.22 Flawed scanline Returns Address of Deallocated Space

67 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-67 Chapter Review (1/2) Strings in C are arrays of characters ended by the null character ‘\0’ Using scanf and fscanf with %s descriptors for strings seperated by whitespace Using getchar and getc for single character input Using printf and fprintf with %s descriptors for string output, putchar and putc do single-character input strcpy and strncpy is used for string assignment and extraction of substrings. strcat and strncat is used for concatenation strlen is used for string length strcmp and strncmp is used for alphabetic comparison

68 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-68 Chapter Review (2/2) The standard I/O library includes functions for string-to-number (sscanf) and number-to-string (sprintf) conversion. String-building functions typically require the calling module to provide space for the new string as an output parameter, and they return the address of this parameter as the function result. The ctype library provides functions for classification and conversion of single characters.

69 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-69 Question?

70 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-70 Programming Projects 2 A resistor is a circuit device designed to have a specific resistance value between its ends. Resistance values are expressed in ohms or kilo-ohms. Resistors are frequently marked with colored bands that encode their resistance values, as shown in Fig. 9.23. The first two bands are digits, and the third is a power-of-ten multiplier.

71 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-71 Figure 9.23 Bands Encoding the Resistance Value of a Resistor

72 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-72 Curses library man curses –cc [ flag... ] file...- lcurses [ library... ] –#include An example… #include main(){ int key; initscr(); cbreak(); noecho(); move(10,0); printw("123 == %d\n", 123); refresh(); while( (key=getch()) != 27 /* ESC */) { printw("[%c]",key); refresh(); }


Download ppt "Chapter 9 Strings Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪."

Similar presentations


Ads by Google