1 / 27

Representing Strings and String I/O

Representing Strings and String I/O. Introduction. A string is a sequence of characters and is treated as a single data item. A string constant, also termed a string literal, is anything enclosed in double quotation marks . p rintf (“Hello world”);

Télécharger la présentation

Representing Strings and String I/O

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Representing Strings and String I/O

  2. Introduction • A string is a sequence of characters and is treated as a single data item. • A string constant, also termed a string literal, is anything enclosed in double quotation marks. printf(“Hello world”); • To use a double quotation mark within a string, precede the quotation mark with a backslash (\) printf(“\”Run, Spot, run!\” exclaimed Dick.\n”);

  3. Introduction • C standard library provides many functions specifically designed to work with strings. • Reading and writing strings. • Combining strings together. • Copying one string to another. • Comparing strings for equality. • Extracting a portion of a string

  4. Declaring and initializing string variables C does not support strings as a data type The only support for strings in the C is that the compiler will translate a quoted string constant into a null-terminated string, which is stored in static memory. The general form of declaration of a string variable is charstring_name[size]; Examples: charcity[10]; char name[30]; A string is a char array terminated with a null character (\0). char city[9] = ”Seoul”; char city[9] = {‘S’, ‘e’, ‘o’, ‘u’, ‘l’, ‘\0’}; string length [] array notation

  5. Declaring and initializing string variables • C permits us to initialize a character array without specifying the number of elements. char string [] = {‘G’, ‘O’, ‘O’, ‘D’, ‘\0’}; • The string can be declared with much larger size then the string size In the initializer. charstr[10] = “GOOD”. Set to zeros

  6. Reading strings from terminal • The familiar input function scanffunction can be used with %s format specifier. char city[10]; scanf(“%s”, city); • scanf()terminates its input on the first white space it finds. • white space include: • blanks, • tabs • new lines. • If the following line of text is typed in at the terminal, NEW YORK Then only “NEW” will be read into the array address. The ampersand (&) is not required before the variable name. Because city is already address in memory where string is stored.

  7. Writing strings to screen • The format %s in the printffunction can be used to display an array of characters that is terminated by the null character. printf(“%s”, name); • We can specify the precision with which the array is displayed. printf(“%10.4s”, name); or printf(“%-10.4s”, name); %10.4 indicates that the first four characters are to be printed in a field width of 10 columns. %-10.4, the string will be printed left-justified

  8. Example • The printfsupport feature that allows for variable field width. printf(“%*.*s\n”, w, d, string) • printfthe first d characters of the string in the field width of w.

  9. Alternative to printf() • We can use putchar() to output the values of a string. charch = ‘A’; putchar (ch). • We can use this function repeatedly to print out a string. char name [6] = “PARIS”; for (I = 0; I < 5; i++) putchar(name[i]); putchar(‘\n’) • Another convenient way of printing string values is to use the function puts. puts (str);

  10. Example

  11. Each string has an address Very important example! • The %s format should print the string We. • The %p format produces an address. So if the phrase "are" is an address, then %p should print the address of the first character in the string. Character located at the address “space travellers” Address of “are”

  12. Missing Operators • There is no string assignment operators. • There are not string comparison operators. • There are not string combination operators. • However, there are built-in functions to do this common tasks. String functions prototypes defined in <string.h>

  13. Built-in String Functions • String assignment. There is no ‘=‘ for string but there isstrcpy( destination, source )char name[ 25 ]; /* contains nothing */strcpy( name, “Hilton” ); /* name now contains “Hilton” */ • String comparison. There is no != for string but there isstrcmp( strA, strB ); • If strA comes after strB, the function returns a positive number. • Is strB comes last, the function returns a negative number. • If strA and strB are the same thing, the function returns a zero. result = strcmp( “CMSC”, “IFSM” ); /* negative */ result = strcmp( “IFSM”, “CMSC” ); /* positive */ result = strcmp( “CMSC”, “CMSC” ); /* zero */

  14. Built-in String Functions (cont’d) • String combination:strcat( destination, source ) • The source is not changed. • The destination contain exactly what it had before plus what was in the source. Nothing else is added. NOTE: If you are combining a first name and last name for a full name, you must use another strcat to add the space between them:strcpy( fullName, firstName);strcat( fullName, “ “ );strcat( fullName, lastName );

  15. Built-in String Functions (cont’d) • Extracting words (tokens) from a string: /* get the first token (delimited by a blank) */ printf( "%s\n", strtok( str, " " ) ); /* This is more useful after you learn to use pointers. */

  16. Built-in String Functions (cont’d) • What if I want to get a menu choice, that is the numbers 1 to 4 or the char ‘q’? Use getchar( ) to get the menu choice, check for ‘q’ and if it is not, then convert it to a number. /* convert a string (ASCII) to an integer */ printf( "%d\n", atoi( "1234" ) ); /* convert a string (ASCII) to a float */ printf( "%f\n", atof( "1234.5678" ) ); • How long is the data in the string (not counting the null terminator)? stringSize = strlen( strA );

  17. String Libraries #include files: #include <stdlib.h> /* needed by atoi( ) and atof( ) */ #include <string.h> /* needed by str...( ) functions */

  18. Sample Program

  19. Sample Program

  20. Sample Program Output string a is >Excellence< After strcpy(b, a), string b is now >Excellence< ============= String b = >Excellence< and is 10 characters long After strcat(b, " "), string b = >Excellence < and is 11 characters long After strcat(b, a), string b = >Excellence Excellence< and is 21 characters long strtok( b, " " ) gives Excellence

  21. Sample Program Output (cont’d) ============= string a = Excellence string c = Failure strcmp( a, c ) gives -1 strcmp( c, a ) gives 1 strcmp( a, "Excellence" gives 0 After strcmp( "CMSC", "IFSM" ), result is -1 After strcmp( "IFSM", "CMSC" ), result is 1 After strcmp( "CMSC", "CMSC" ), result is 0

  22. Sample Program Output (cont’d) ============= atoi( "1234”) gives 1234 atof( "1234.5678" ) gives 1234.567800

  23. Other String Functions The statement copies first n characters of the source string s2 into the target string s1. • Since the first ncharacters may not include the terminating null character, we have to place it explicitly in the 6th position of s2 s1[n+1] = ‘\0’; This compares the left-most n characters of s1 to s2 and returns. • 0 if the are equal; • Negative number if s1 sub-string is less than s2; and • Positive number , otherwise.

  24. Other String Functions • Concatenate the left-most n characters of s2 to the end of s1. s1 s2 after(s1, s2, 6) • s1 is a string to search within. • s2 is the substring that you want to find.

  25. Array Versus Pointer* You can use pointer notation to set up a string. const char *m3 = "\nEnough about me -- what's your name?"; This declaration is very nearly the same as this one:char m3[] = "\nEnough about me -- what's your name?" In short, initializing the array copies a string from static storage to the array, whereas initializing the pointer merely copies the address of the string. char heart[] = "I love Tillie!"; char *head = "I love Millie!"; The difference is that the array name heart is a constant, but the pointer head is a variable. head = heart; /* head now points to the array heart */ heart = head; /* illegal construction */

  26. Example: reverse characters in an input string

  27. Passing parameter to the main function

More Related