1 / 64

C Program Design C Characters and Strings

C Program Design C Characters and Strings. 主講人:虞台文. Content. Introduction Fundamentals of Strings and Characters Character-Handling Library String-Conversion Functions Standard Input/Output Library Functions String-Manipulation Functions of the String-Handling Library

berne
Télécharger la présentation

C Program Design C Characters and Strings

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. C Program DesignC Characters and Strings 主講人:虞台文

  2. Content • Introduction • Fundamentals of Strings and Characters • Character-Handling Library • String-Conversion Functions • Standard Input/Output Library Functions • String-Manipulation Functions of the String-Handling Library • Comparison Functions of the String-Handling Library • Search Functions of the String-Handling Library • Memory Functions of the String-Handling Library • Other Functions of the String-Handling Library

  3. C Program DesignC Characters and Strings Introduction

  4. Main Topics • Introduce some standard library functions • Easy string and character processing • Programs can process characters, strings, lines of text, and blocks of memory • These techniques used to make • Word processors • Page layout software • Typesetting programs • Database maintenance routines • . . .

  5. Some Character/String Libraries • stdio.h • string and character input/output • ctype.h • character-handling • stdlib.h • String/number conversion • string.h • string-processing

  6. C Program DesignC Characters and Strings Fundamentals of Strings and Characters

  7. Characters and Strings • Characters • Building blocks of text (strings) • ASCII (American Standard Code for Information Interchange) • Character constant • An int value represented as a character in single quotes • 'z' represents the integer value of z • Strings • Series of characters treated as a single unit • String literal (string constant) - written in double quotes • "Hello\n" • Strings are arrays of null terminated characters • String is represented by a pointer to first character • Value of string is the address of first character

  8. h (68) e (65) l (6C) l (6C) o (6F) \n (0A) \0 (00) Strings in C • Null-terminated string In C, a string is a character array terminated with a '\0' to mark the end. sizeof(str) = 7 Example: str str[0] str[1] str[2] char str[]="hello"; str[3] str[4] str[5] str[6] char str[]={'h','e','l','l','o','\n','\0'};

  9. color[0] b (62) color[1] l (6C) color[2] u (75) color[3] e (65) color[4] \0 (00) colorPtr[0] b (62) colorPtr[1] l (6C) colorPtr[2] u (75) colorPtr[3] e (65) colorPtr[4] \0 (00) String Definition • Define as • a character array; or • a variable of typechar * char color[] = "blue"; char *colorPtr = "blue"; color colorPtr sizeof(color) = ? sizeof(colorPtr) = ?

  10. color[0] b (62) color[1] l (6C) color[2] u (75) color[3] e (65) color[4] \0 (00) colorPtr[0] b (62) colorPtr[1] l (6C) colorPtr[2] u (75) colorPtr[3] e (65) colorPtr[4] \0 (00) String Definition • Define as • a character array; or • a variable of typechar * char color[] = "blue"; char *colorPtr = "blue"; color colorPtr Can we write ? colorPtr = color; color = colorPtr;  

  11. String Definition #include <stdio.h> main() { char strHelloArray[] = "Hello defined by char[]\n"; char *strHelloPointer = "Hello defined by char*\n"; // Using string defined by char[] printf("char strHelloArray[] = \"Hello defined by char[]\\n\"\n"); printf("\nprintf(strHelloArray);//=printf(\"Hello defined by char[]\\n\");\n"); printf(strHelloArray); printf("\n\n"); // Using string defined by char* printf("char *strHelloPointer = \"Hello defined by char*\\n\"\n"); printf("\nprintf(strHelloPointer);// = printf(\"Hello defined by char*\\n\");\n"); printf(strHelloPointer); }

  12. String Definition #include <stdio.h> main() { char strHelloArray[] = "Hello defined by char[]\n"; char *strHelloPointer = "Hello defined by char*\n"; // Using string defined by char[] printf("char strHelloArray[] = \"Hello defined by char[]\\n\"\n"); printf("\nprintf(strHelloArray);//=printf(\"Hello defined by char[]\\n\");\n"); printf(strHelloArray); printf("\n\n"); // Using string defined by char* printf("char *strHelloPointer = \"Hello defined by char*\\n\"\n"); printf("\nprintf(strHelloPointer);// = printf(\"Hello defined by char*\\n\");\n"); printf(strHelloPointer); }

  13. sizeof() #include <stdio.h> main() { char strHelloArray[] = "Hello defined by char[]\n"; char *strHelloPointer = "Hello defined by char*\n"; // Using string defined by char[] printf("char strHelloArray[] = \"Hello defined by char[]\\n\"\n"); printf("\nprintf(strHelloArray);//=printf(\"Hello defined by char[]\\n\");\n"); printf(strHelloArray); printf("\n\n"); // Using string defined by char* printf("char *strHelloPointer = \"Hello defined by char*\\n\"\n"); printf("\nprintf(strHelloPointer);// = printf(\"Hello defined by char*\\n\");\n"); printf(strHelloPointer); } #include <stdio.h> main() { char strHelloArray[] = "Hello defined by char[]\n"; char *strHelloPointer = "Hello defined by char*\n"; // Using string defined by char[] printf("char strHelloArray[] = \"Hello defined by char[]\\n\"\n"); printf("\nprintf(strHelloArray);//=printf(\"Hello defined by char[]\\n\");\n"); printf(strHelloArray); printf("\n\n"); // Using string defined by char* printf("char *strHelloPointer = \"Hello defined by char*\\n\"\n"); printf("\nprintf(strHelloPointer);// = printf(\"Hello defined by char*\\n\");\n"); printf(strHelloPointer); // print out the sizeof each data type printf("\nsizeof(strHelloArray)=%d, sizeof(strHelloPointer)=%d.\n", sizeof(strHelloArray), sizeof(strHelloPointer)); }

  14. Read String into an Array char word[20]; scanf("%s", word); // at the risk of overflow scanf("%19s", word); // a safe version

  15. C Program DesignC Characters and Strings Character Handling Library

  16. ctype.h

  17. ctype.h

  18. Read a line of text and do something for each character in the line using all functions in <ctype.h>. Example: #include <stdio.h> #include <ctype.h> #include <stdlib.h> main() { int c; while((c = getchar()) != EOF){ if(c=='\n') break; // test predicates for characters printf("%c is %sa digit character.\n", c, isdigit(c) ? "" : "not "); printf("%c is %san alpha character.\n", c, isalpha(c) ? "" : "not "); printf("%c is %san alnum character.\n", c, isalnum(c) ? "" : "not "); printf("%c is %sa xdigit character.\n", c, isxdigit(c) ? "" : "not "); printf("%c is %sa lower character.\n", c, islower(c) ? "" : "not "); printf("%c is %san upper character.\n", c, isupper(c) ? "" : "not "); printf("%c is %sa space character.\n", c, isspace(c) ? "" : "not "); printf("%c is %sa cntrl character.\n", c, iscntrl(c) ? "" : "not "); printf("%c is %sa punct character.\n", c, ispunct(c) ? "" : "not "); printf("%c is %sa print character.\n", c, isprint(c) ? "" : "not "); printf("%c is %sa graph character.\n", c, isgraph(c) ? "" : "not "); // test character convertions printf("convert %c to upper --> %c\n", c, toupper(c)); printf("convert %c to lower --> %c\n", c, tolower(c)); } system("pause"); }

  19. Read a line of text and do something for each character in the line using all functions in <ctype.h>. Example: #include <stdio.h> #include <ctype.h> #include <stdlib.h> main() { int c; while((c = getchar()) != EOF){ if(c=='\n') break; // test predicates for characters printf("%c is %sa digit character.\n", c, isdigit(c) ? "" : "not "); printf("%c is %san alpha character.\n", c, isalpha(c) ? "" : "not "); printf("%c is %san alnum character.\n", c, isalnum(c) ? "" : "not "); printf("%c is %sa xdigit character.\n", c, isxdigit(c) ? "" : "not "); printf("%c is %sa lower character.\n", c, islower(c) ? "" : "not "); printf("%c is %san upper character.\n", c, isupper(c) ? "" : "not "); printf("%c is %sa space character.\n", c, isspace(c) ? "" : "not "); printf("%c is %sa cntrl character.\n", c, iscntrl(c) ? "" : "not "); printf("%c is %sa punct character.\n", c, ispunct(c) ? "" : "not "); printf("%c is %sa print character.\n", c, isprint(c) ? "" : "not "); printf("%c is %sa graph character.\n", c, isgraph(c) ? "" : "not "); // test character convertions printf("convert %c to upper --> %c\n", c, toupper(c)); printf("convert %c to lower --> %c\n", c, tolower(c)); } system("pause"); }

  20. C Program DesignC Characters and Strings String-Conversion Functions

  21. stdlib.h

  22. Example: #include <stdlib.h> #include <stdio.h> #include <errno.h> int main( void ) { char *str = NULL; int value = 0; // An example of the atoi function. str = " -2309 ";// with leading space & sign value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); // Another example of the atoi function. str = "31412764"; value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); // Another example of the atoi function // with an overflow condition occuring. str = "3336402735171707160320"; // too large value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); if (errno == ERANGE){ printf("Overflow condition occurred.\n"); } }

  23. Example: #include <stdlib.h> #include <stdio.h> #include <errno.h> int main( void ) { char *str = NULL; int value = 0; // An example of the atoi function. str = " -2309 ";// with leading space & sign value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); // Another example of the atoi function. str = "31412764"; value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); // Another example of the atoi function // with an overflow condition occuring. str = "3336402735171707160320"; // too large value = atoi( str ); printf( "Function: atoi( \"%s\" ) = %d\n", str, value ); if (errno == ERANGE){ printf("Overflow condition occurred.\n"); } }

  24. #include <stdlib.h> #include <stdio.h> int main( void ) { char *string, *stopstring; double x; long l; int base; unsigned long ul; string = "3.1415926This stopped it"; x = strtod( string, &stopstring ); printf( "string = %s\n", string ); printf(" strtod = %f\n", x ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "-10110134932This stopped it"; l = strtol( string, &stopstring, 10 ); printf( "string = %s\n", string ); printf(" strtol = %ld\n", l ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "10110134932"; printf( "string = %s\n", string ); // Convert string using base 2, 4, and 8: for( base = 2; base <= 8; base *= 2 ) { // Convert the string: ul = strtoul( string, &stopstring, base ); printf( " strtol = %ld (base %d)\n", ul, base ); printf( " Stopped scan at: %s\n", stopstring ); } } Example:

  25. #include <stdlib.h> #include <stdio.h> int main( void ) { char *string, *stopstring; double x; long l; int base; unsigned long ul; string = "3.1415926This stopped it"; x = strtod( string, &stopstring ); printf( "string = %s\n", string ); printf(" strtod = %f\n", x ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "-10110134932This stopped it"; l = strtol( string, &stopstring, 10 ); printf( "string = %s\n", string ); printf(" strtol = %ld\n", l ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "10110134932"; printf( "string = %s\n", string ); // Convert string using base 2, 4, and 8: for( base = 2; base <= 8; base *= 2 ) { // Convert the string: ul = strtoul( string, &stopstring, base ); printf( " strtol = %ld (base %d)\n", ul, base ); printf( " Stopped scan at: %s\n", stopstring ); } } Example:

  26. C Program DesignC Characters and Strings Standard Input/Output Library Functions

  27. stdio.h

  28. Example: gets, putchar /* Using gets and putchar */ #include <stdio.h> void reverse( const char * const sPtr ); /* prototype */ int main( void ) { char sentence[ 80 ]; /* create char array */ printf( "Enter a line of text:\n" ); /* use gets to read line of text */ gets( sentence ); printf( "\nThe line printed backward is:\n" ); reverse( sentence ); putchar('\n'); return 0; /* indicates successful termination */ } /* end main */

  29. Example: gets, putchar /* recursively outputs characters in string in reverse order */ void reverse( const char * const sPtr ) { /* if end of the string */ if ( sPtr[ 0 ] == '\0' ) return; /* if not end of the string */ reverse( &sPtr[ 1 ] ); /* recursion step */ putchar( sPtr[ 0 ] ); /* use putchar to display character */ } /* end function reverse */ /* Using gets and putchar */ #include <stdio.h> void reverse( const char * const sPtr ); /* prototype */ int main( void ) { char sentence[ 80 ]; /* create char array */ printf( "Enter a line of text:\n" ); /* use gets to read line of text */ gets( sentence ); printf( "\nThe line printed backward is:\n" ); reverse( sentence ); putchar('\n'); return 0; /* indicates successful termination */ } /* end main */

  30. Example: gets, putchar /* recursively outputs characters in string in reverse order */ void reverse( const char * const sPtr ) { /* if end of the string */ if ( sPtr[ 0 ] == '\0' ) return; /* if not end of the string */ reverse( &sPtr[ 1 ] ); /* recursion step */ putchar( sPtr[ 0 ] ); /* use putchar to display character */ } /* end function reverse */ /* recursively outputs characters in string in reverse order */ void reverse( const char * const sPtr ) { /* if end of the string */ if ( *sPtr == '\0' ) return; /* if not end of the string */ reverse( sPtr + 1 ); /* recursion step */ putchar( *sPtr ); /* use putchar to display character */ } /* end function reverse */

  31. Example: sprintf, puts /* Using sprintf, puts */ #include <stdio.h> int main( void ) { char s[ 80 ]; /* create char array */ int x; /* x value to be input */ double y; /* y value to be input */ printf( "Enter an integer and a double:\n" ); scanf( "%d%lf", &x, &y ); sprintf( s, "integer:%6d\ndouble:%8.2f", x, y ); puts( s ); return 0; /* indicates successful termination */ } /* end main */

  32. Example: sscanf /* Using sprintf, puts */ #include <stdio.h> int main( void ) { char s[ 80 ]; /* create char array */ int x; /* x value to be input */ double y; /* y value to be input */ char *input = "15 3.14\n"; printf( "Enter an integer and a double:\n" ); sscanf( input, "%d%lf", &x, &y ); sprintf( s, "integer:%6d\ndouble:%8.2f", x, y ); puts( s ); return 0; /* indicates successful termination */ } /* end main */

  33. C Program DesignC Characters and Strings String Manipulation Functions of the String Handling Library

  34. string.h • String handling library has functions to • Manipulate string data • Search strings • Tokenize strings • Determine string length

  35. string.h

  36. string.h Type size_t is a system-dependent synonym for either type unsigned long or type unsigned int.

  37. Example: strcpy, strncpy /* Using strcpy and strncpy */ #include <stdio.h> #include <string.h> int main( void ) { char x[] = "Happy Birthday to You"; /* initialize char array x */ char y[ 25 ]; /* create char array y */ char z[ 15 ]; /* create char array z */ /* copy contents of x into y */ printf( "%s%s\n%s%s\n", "The string in array x is: ", x, "The string in array y is: ", strcpy( y, x ) ); /* copy first 14 characters of x into z. Does not copy null character */ strncpy( z, x, 14 ); z[ 14 ] = '\0'; /* terminate string in z */ printf( "The string in array z is: %s\n", z ); return 0; /* indicates successful termination */ } /* end main */

  38. Example: strcat, strncat /* Using strcat and strncat */ #include <stdio.h> #include <string.h> int main( void ) { char s1[ 20 ] = "Happy "; /* initialize char array s1 */ char s2[] = "New Year "; /* initialize char array s2 */ char s3[ 40 ] = ""; /* initialize char array s3 to empty */ printf( "s1 = %s\ns2 = %s\n", s1, s2 ); /* concatenate s2 to s1 */ printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) ); /* concatenate first 6 characters of s1 to s3. Place '\0' after last character */ printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) ); /* concatenate s1 to s3 */ printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) ); return 0; /* indicates successful termination */ } /* end main */

  39. C Program DesignC Characters and Strings Comparison Functions of the String-Handling Library

  40. string.hString Comparison

  41. Example: strcmp, strncmp /* Using strcmp and strncmp */ #include <stdio.h> #include <string.h> int main( void ) { const char *s1 = "Happy New Year"; /* initialize char pointer */ const char *s2 = "Happy New Year"; /* initialize char pointer */ const char *s3 = "Happy Holidays"; /* initialize char pointer */ printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n", "s1 = ", s1, "s2 = ", s2, "s3 = ", s3, "strcmp(s1, s2) = ", strcmp( s1, s2 ), "strcmp(s1, s3) = ", strcmp( s1, s3 ), "strcmp(s3, s1) = ", strcmp( s3, s1 ) ); printf("%s%2d\n%s%2d\n%s%2d\n", "strncmp(s1, s3, 6) = ", strncmp( s1, s3, 6 ), "strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ), "strncmp(s3, s1, 7) = ", strncmp( s3, s1, 7 ) ); return 0; /* indicates successful termination */ } /* end main */

  42. Example: strcmp, strncmp /* Using strcmp and strncmp */ #include <stdio.h> #include <string.h> int main( void ) { const char *s1 = "Happy New Year"; /* initialize char pointer */ const char *s2 = "Happy New Year"; /* initialize char pointer */ const char *s3 = "Happy Holidays"; /* initialize char pointer */ printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n", "s1 = ", s1, "s2 = ", s2, "s3 = ", s3, "strcmp(s1, s2) = ", strcmp( s1, s2 ), "strcmp(s1, s3) = ", strcmp( s1, s3 ), "strcmp(s3, s1) = ", strcmp( s3, s1 ) ); printf("%s%2d\n%s%2d\n%s%2d\n", "strncmp(s1, s3, 6) = ", strncmp( s1, s3, 6 ), "strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ), "strncmp(s3, s1, 7) = ", strncmp( s3, s1, 7 ) ); return 0; /* indicates successful termination */ } /* end main */

  43. C Program DesignC Characters and Strings Search Functions of the String-Handling Library

  44. string.hString Search

  45. string.hString Search

  46. #include <string.h> #include <stdio.h> int ch = 'r'; char string[] = "The quick brown dog jumps over the lazy fox"; char fmt1[] = " 1 2 3 4 5"; char fmt2[] = "12345678901234567890123456789012345678901234567890"; int main( void ) { char *pdest; int result; printf( "String to be searched:\n %s\n", string ); printf( " %s\n %s\n\n", fmt1, fmt2 ); printf( "Search char: %c\n", ch ); // Search forward. pdest = strchr( string, ch ); result = (int)(pdest - string + 1); if ( pdest != NULL ) printf( "Result: first %c found at position %d\n", ch, result ); else printf( "Result: %c not found\n" ); // Search backward. pdest = strrchr( string, ch ); result = (int)(pdest - string + 1); if ( pdest != NULL ) printf( "Result: last %c found at position %d\n", ch, result ); else printf( "Result:\t%c not found\n", ch ); } Example: strchr, strrchr

  47. #include <string.h> #include <stdio.h> int ch = 'r'; char string[] = "The quick brown dog jumps over the lazy fox"; char fmt1[] = " 1 2 3 4 5"; char fmt2[] = "12345678901234567890123456789012345678901234567890"; int main( void ) { char *pdest; int result; printf( "String to be searched:\n %s\n", string ); printf( " %s\n %s\n\n", fmt1, fmt2 ); printf( "Search char: %c\n", ch ); // Search forward. pdest = strchr( string, ch ); result = (int)(pdest - string + 1); if ( pdest != NULL ) printf( "Result: first %c found at position %d\n", ch, result ); else printf( "Result: %c not found\n" ); // Search backward. pdest = strrchr( string, ch ); result = (int)(pdest - string + 1); if ( pdest != NULL ) printf( "Result: last %c found at position %d\n", ch, result ); else printf( "Result:\t%c not found\n", ch ); } Example: strchr, strrchr

  48. Example: strcspn /* Using strcspn */ #include <stdio.h> #include <string.h> int main( void ) { /* initialize two char pointers */ const char *string1 = "The value is 3.14159"; const char *string2 = "1234567890"; printf( "%s%s\n%s%s\n\n%s\n%s%u\n", "string1 = ", string1, "string2 = ", string2, "The length of the initial segment of string1", "containing no characters from string2 = ", strcspn( string1, string2 ) ); return 0; /* indicates successful termination */ } /* end main */

  49. Example: strpbrk #include <string.h> #include <stdio.h> int main( void ) { char string[100] = "The 3 men and 2 boys ate 5 pigs\n"; char *result = NULL; // Return pointer to first digit in "string". printf( "1: %s\n", string ); result = strpbrk( string, "0123456789" ); printf( "2: %s\n", result++ ); result = strpbrk( result, "0123456789" ); printf( "3: %s\n", result++ ); result = strpbrk( result, "0123456789" ); printf( "4: %s\n", result ); }

  50. Example: strspn // This program uses strspn to determine // the length of the segment in the string "cabbage" // consisting of a's, b's, and c's. In other words, // it finds the first non-abc letter. // #include <string.h> #include <stdio.h> int main( void ) { char string[] = "cabbage"; int result; result = strspn( string, "abc" ); printf( "The portion of '%s' containing only a, b, or c " "is %d bytes long\n", string, result ); }

More Related