Chapter 9 Strings 20061213 chap 9 Strings n

  • Slides: 33
Download presentation
Chapter 9 Strings 20061213 chap 9

Chapter 9 Strings 20061213 chap 9

Strings n n n A data structure deals with a grouping of characters. C

Strings n n n A data structure deals with a grouping of characters. C implements the string data structure using arrays of type char. Numerical data & textural data. Typewriter Computer-based word processing systems You have already used the string extensively. printf(“This program is terminated!n”); #define ERR_Message “Error!!” 20061213 chap 9 2

Declaring & Initializing String Variables n Since string is an array, the declaration of

Declaring & Initializing String Variables n Since string is an array, the declaration of a string is the same as declaring a char array. char string_var[30]; char string_var[20] = “Initial value”; [13] [0] I n n n i t i a l v a l u e ? ? … The string is always ended with a null character ‘’ The characters after the null character are ignored. 20061213 chap 9 3

Arrays of Strings n n One string is an array of characters. An array

Arrays of Strings n n One string is an array of characters. An array of strings is a two-dimensional array of characters in which each row is one string. char names[People][Length]; char month[5][10] = {“January”, “February”, “March”, “April”, “May”}; 20061213 chap 9 4

I/O with printf and scanf n The placeholder %s is used to represent string

I/O with printf and scanf n The placeholder %s is used to represent string arguments in printf and scanf. printf(“Topic: %sn”, string_var); n The string can be right-justified by placing a positive number in the placeholder. printf(“%8 s”, str); %8 s n The string can be left-justified by placing a negative number in the placeholder. printf(“%-8 s”, str); %-8 s 20061213 chap 9 5

Right- and Left-Justified Strings n The “%8 s” %8 s placeholder displays a string

Right- and Left-Justified Strings n The “%8 s” %8 s placeholder displays a string which is right-justified and in 8 -columns width. n If the actual string is longer than the width, the displayed field is expanded with no padding. 20061213 chap 9 6

Example (Fig. 9. 2) The dept is the initial memory address of the string

Example (Fig. 9. 2) The dept is the initial memory address of the string argument. Thus we don’t apply the & operator on it. 20061213 chap 9 7

Execution of scanf ("%s", dept); n n Whenever encountering a white space, the scanning

Execution of scanf ("%s", dept); n n Whenever encountering a white space, the scanning stops and scanf places the null character at the end of the string. e. g. , if the user types “MATH 1234 TR 1800, ” the string “MATH” along with ‘’ is stored into dept. 20061213 chap 9 8

Entry of Invalid Data scanf("%s%d", dept, &course_num, days, &time); > MATH, 1270, TR, 1800

Entry of Invalid Data scanf("%s%d", dept, &course_num, days, &time); > MATH, 1270, TR, 1800 20061213 chap 9 9

String Library Functions n The string can not be copied by the assignment operator

String Library Functions n The string can not be copied by the assignment operator ‘=’. str = “Test String” --- not valid. n C provides string manipulating functions in the “string. h” library. n 20061213 The complete list of these functions can be found in Appendix B of the textbook. chap 9 10

String Library Functions from string. h 20061213 chap 9 11

String Library Functions from string. h 20061213 chap 9 11

String Assignment n Function strcpy copies the string in the second argument into the

String Assignment n Function strcpy copies the string in the second argument into the first argument. char one-str[20]; strcpy(one_str, “test string”); The null character is appended at the end automatically. n n If source string is longer than the destination string, the overflow characters may occupy the memory space used by other variables. BAD: The value of these other variables would seem to change spontaneously. On rare occasions, such overflow would generate a run-time error message. strcpy(one_str, “A very long test string”); 20061213 chap 9 12

strcpy vs. strncpy n n Function strncpy copies the string by specifying the number

strcpy vs. strncpy n n Function strncpy copies the string by specifying the number of characters to copy. If source string is longer than the destination string, the overflow characters are discarded automatically. strncpy(dest, source, dest_len-1); dest[dest_len-1] = ‘’; //To place the null char. manually. 20061213 chap 9 13

Substrings n n We frequently need to reference a substring of a longer character

Substrings n n We frequently need to reference a substring of a longer character string. We can use strncpy to copy a middle or an ending portion of a string. char *strncpy(char *dest, const char *source, size_t n); 20061213 chap 9 14

Example of substring char result[10]; char s 1[15] = “Jan. 30, 1996”; strncpy(result, s

Example of substring char result[10]; char s 1[15] = “Jan. 30, 1996”; strncpy(result, s 1, 9); results[9]= ‘’; 20061213 chap 9 15

Another example of substring n n strncpy(result, &s 1[5], 2); results[2]= ‘�’; 20061213 chap

Another example of substring n n strncpy(result, &s 1[5], 2); results[2]= ‘’; 20061213 chap 9 16

Separate compounds into elemental components (Fig. 9. 7) 20061213 chap 9 17

Separate compounds into elemental components (Fig. 9. 7) 20061213 chap 9 17

String Concatenation n Functions strcat and strncat concatenate the fist string argument with the

String Concatenation n Functions strcat and strncat concatenate the fist string argument with the second string argument. char f 1[15] = “John ”, f 2[15] = “Jacqueline ”, last[15] = “Kennedy”; strcat(f 1, last); strcat(f 2, last); /* invalid overflow */ strncat(f 2, last, 3); 20061213 chap 9 18

String Length n n When writing a string-manipulating program, one usually does not know

String Length n n When writing a string-manipulating program, one usually does not know in advance the sizes of the string used as data. Function strlen is often used to check the length of a string (i. e. , the number of characters before the first null character). dest[6] = “Hello”; strncat(dest, “more”, 5 strlen(dest)); dest[5] = ‘’; 20061213 chap 9 19

Characters vs. Strings n The representation of a char (e. g. , ‘Q’) and

Characters vs. Strings n The representation of a char (e. g. , ‘Q’) and a string (e. g. , “Q”) is essentially different. n A string is an array of characters ended with the null character. Q Character ‘Q’ 20061213 chap 9 Q String “Q” 20

String Comparison n Suppose there are two strings, str 1 and str 2. n

String Comparison n Suppose there are two strings, str 1 and str 2. n n The comparison between two strings is done by comparing each corresponding character in them. n n The condition str 1 < str 2 compare the initial memory address of str 1 and of str 2. The characters are compared against the ASCII table. “thrill” < “throw” since ‘i’ < ‘o’ “joy” < “joyous” The standard string comparison uses the strcmp and strncmp functions. 20061213 chap 9 21

String Comparison Relationship str 1 < str 2 str 1 = str 2 str

String Comparison Relationship str 1 < str 2 str 1 = str 2 str 1 > str 2 n Returned Value Example Negative “Hello”< “Hi” 0 “Hi” = “Hi” Positive “Hi” > “Hello” e. g. , we can check if two strings are the same by if(strcmp(str 1, str 2) != 0) printf(“The two strings are different!”); 20061213 chap 9 22

Numeric and String Versions of Portions of Selection Sort That Compare and Exchange Elements

Numeric and String Versions of Portions of Selection Sort That Compare and Exchange Elements 20061213 chap 9 23

Sentinel-Controlled Loop for String Input 20061213 chap 9 24

Sentinel-Controlled Loop for String Input 20061213 chap 9 24

Arrays of Pointers 20061213 chap 9 25

Arrays of Pointers 20061213 chap 9 25

Arrays of Pointers n char *alphap[5]; 20061213 chap 9 26

Arrays of Pointers n char *alphap[5]; 20061213 chap 9 26

I/O of Characters and Strings n The stdio library provides getchar function which gets

I/O of Characters and Strings n The stdio library provides getchar function which gets the next character from the standard input. n n n “ch = getchar(); ” is the same as “scanf(“%c”, &ch); ” Similar functions are putchar, gets, puts. For IO from/to the file, the stdio library also provides corresponding functions. n n 20061213 getc: reads a character from a file. Similar functions are putc, fgets, fputs. chap 9 27

Character Analysis and Conversion n The <ctype. h> library defines facilities for character analysis

Character Analysis and Conversion n The <ctype. h> library defines facilities for character analysis and conversion. Functions isalpha isdigit isspace tolower 20061213 chap 9 Description Check if the argument is a letter Check if the argument is one of the ten digits Check if argument is a space, newline or tab. Converts the lowercase letters in the argument to upper case letters. 28

String-to-Number and Number-to-String n The <stdlib. h> defines some basic functions for conversion from

String-to-Number and Number-to-String n The <stdlib. h> defines some basic functions for conversion from strings to numbers: n n atoi(“ 123”) converts a string to an integer. atol(“ 123”) converts a string to a long integer. atof(“ 12. 3”) converts a string to a float. However, there is no functions such as itoa, …etc, n 20061213 because there is a function called sprintf which can converts many formats to a string. chap 9 29

sprintf and sscanf n The sprintf function substitutes values for placeholders just as printf

sprintf and sscanf n The sprintf function substitutes values for placeholders just as printf does except that it stores the result into a character array sprintf(s, “%d%d%d”, mon, day, year); n The sscanf function works exactly like scanf except that it takes data from the string as its input argument. sscanf(“ 11 22. 2 Hello”, “%d%lf%s”, &num, &val, word); 20061213 chap 9 30

Demo: Text Editor 20061213 chap 9 32

Demo: Text Editor 20061213 chap 9 32

Summary 20061213 chap 9 33

Summary 20061213 chap 9 33