Presentation is loading. Please wait.

Presentation is loading. Please wait.

13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.

Similar presentations


Presentation on theme: "13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal."— Presentation transcript:

1 13. Strings

2 String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may be extended over more than one line by writing \ immediately followed by the end of the line: printf("Put a disk in drive A, then \ press any key to continue\n"); A string literal may be divided into two or more shorter strings; the compiler will join these together into one string: printf("Put a disk in drive A, then " "press any key to continue\n");

3 How String Literals Are Stored The string literal "abc" is represented by the three characters a, b, and c, followed by a null character (\0): Like any array, a string literal is represented by a pointer to the first character in the string. A string literal of length 1 is different from a character constant. A string literal of length 1 ("a", for example) is represented by a pointer. A character constant ('a', for example) is represented by an integer value.

4 How String Literals Are Stored Warning: Don’t ever use a character constant when a string literal is required (or vice-versa). The call printf("\n"); is legal, because printf expects a string as its first parameter, but printf('\n'); is not.

5 String Variables A string variable is just a one-dimensional array of characters: #define STR_LEN 80 char str[STR_LEN+1]; The array should be one character longer than the string it will hold, to leave space for the null character. Warning: Failure to leave room for the null character may cause unpredictable results when using string-handling functions in the C library.

6 String Variables A string variable can be initialized: char date1[8] = "June 14"; The date array will have the following appearance: A string initializer need not completely fill the array: char date2[9] = "June 14"; The leftover array elements are filled with null characters:

7 String Variables If the length of the array is omitted, the compiler will compute it: char date3[] = "June 14"; /* date3 is 8 characters long */

8 Reading and Writing Strings To read or write a string, use scanf or printf with the %s conversion specification: scanf("%s", str); printf("%s", str); scanf skips white space, then reads characters into str until it encounters a white-space character. No ampersand is needed when using scanf to read into a string variable. Since a string variable is an array, the name of the variable is already a pointer (to the beginning of the array).

9 Reading and Writing Strings A faster alternative: Use gets and puts instead of scanf and printf: gets(str); puts(str); gets reads characters into str until it encounters a new- line character. puts prints str, followed by a new-line character. scanf and gets automatically put a null character at the end of the input string. printf and puts assume that the output string ends with a null character.

10 Reading and Writing Strings Warning: Both scanf and gets assume that the string variable is large enough to contain the input string (including the null character at the end). Failing to make the variable long enough will have unpredictable results. To make scanf safer, use the conversion specification %ns, where n specifies the maximum number of characters to be read. Use fgets instead of gets for greater safety.

11 Accessing the Characters in a String Because of the close relationship between arrays and pointers, strings can be accessed either by array subscripting or by pointer reference. Array version of a function that counts the number of spaces in a string: int count_spaces(const char s[]) { int count, i; count = 0; for (i = 0; s[i] != '\0'; i++) if (s[i] == ' ') count++; return count; }

12 Accessing the Characters in a String Pointer version of the same function: int count_spaces(const char *s) { int count; count = 0; for (; *s != '\0'; s++) if (*s == ' ') count++; return count; }

13 Using the C String Library C provides little built-in support for strings. Since strings are treated as arrays, they are restricted in the same ways as arrays—in particular, strings cannot be copied or compared. Warning: Attempts to copy or compare two strings using C’s built-in operators will fail: char str1[10], str2[10]; str1 = str2; /* illegal */ if (str1 == str2)... /* will produce the wrong result */ The C library provides a rich set of functions for performing operations on strings. Declarations for these functions reside in.

14 The strcpy Function strcpy copies one string into another: char str1[10], str2[10]; strcpy(str1, "abcd"); /* str1 now contains "abcd" */ strcpy(str2, str1); /* str2 now contains "abcd" */ strcpy calls can be chained: strcpy(str2, strcpy(str1, "abcd")); /* both str1 and str2 now contain "abcd" */ Warning: strcpy has no way to check that the second string will fit in the first one.

15 The strcat Function strcat appends the contents of one string to the end of another: char str[10] = "abc"; strcat(str, "def"); /* str now contains "abcdef" */ Warning: strcat has no way to check that the first string can accommodate the added characters.

16 The strcmp Function strcmp compares two strings: if (strcmp(str1, str2) < 0)... strcmp returns a value less than, equal to, or greater than 0, depending on whether str1 is less than, equal to, or greater than str2. strcmp considers str1 to be less than str2 if The first i characters of str1 and str2 match, but the (i+1)st character of str1 is less than the (i+1)st character of str2 (for example, "abc" is less than "acc", and "abc" is less than "bcd"), or All characters of str1 match str2, but str1 is shorter than str2 (for example, "abc" is less than "abcd")

17 The strlen Function strlen returns the length of a string: int i; char str[10]; i = strlen("abc"); /* i is now 3 */ i = strlen(""); /* i is now 0 */ strcpy(str, "abc"); i = strlen(str); /* i is now 3 */ When given an array of characters as its argument, strlen does not measure the length of the array itself; instead, it returns the length of the string stored inside the array.

18 Writing the strlen Function Version 1: int strlen(const char *s) { int n; for (n = 0; *s != '\0'; s++) n++; return n; } Version 2: int strlen(const char *s) { int n = 0; for (; *s != 0; s++) n++; return n; }

19 Writing the strlen Function Version 3: int strlen(const char *s) { int n = 0; for (; *s; s++) n++; return n; } Version 4: int strlen(const char *s) { int n = 0; while (*s++) n++; return n; }

20 Writing the strcat Function char *strcat(char *s1, const char *s2) { char *p = s1; while (*p++); --p; while (*p++ = *s2++); return s1; }

21 Arrays of strings char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};

22 Arrays of strings char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};

23 Command line arguments int main(int argc, char *argv[]) { for (i = 1; i < argc; i++) printf("%s\n", argv[i]); } ls -l remind.c


Download ppt "13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal."

Similar presentations


Ads by Google