C Characters and Strings

  • Upload
    canarif

  • View
    228

  • Download
    0

Embed Size (px)

Citation preview

  • 8/6/2019 C Characters and Strings

    1/25

    2000 Prentice Hall, Inc. All rights reserved.

    Chapter 8 - Characters and Strings

    Outline8.1 Introduction

    8.2 Fundamentals of Strings and Characters

    8.3 Character Handling Library8.4 String Conversion Functions

    8.5 Standard Input/Output Library Functions

    8.6 String Manipulation Functions of the String Handling

    Library

    8.7 Comparison Functions of the String Handling Library

    8.8 Search Functions of the String Handling Library8.9 Memory Functions of the String Handling Library

    8.10 Other Functions of the String Handling Library

  • 8/6/2019 C Characters and Strings

    2/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.1 Introduction

    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

  • 8/6/2019 C Characters and Strings

    3/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.2 Fundamentals of Strings and

    Characters

    Characters Building blocks of programs

    Every program is a sequence of meaningfully grouped

    characters

    Character constant - an int value represented as a character

    in single quotes

    'z' represents the integer value ofz

  • 8/6/2019 C Characters and Strings

    4/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.2 Fundamentals of Strings and

    Characters (II)

    Strings Series of characters treated as a single unit

    Can include letters, digits, and certain special characters (*, /,

    $)

    String literal (string constant) - written in double quotes

    "Hello"

    Strings are arrays of characters

    String a pointer to first character

    Value of string is the address of first character

  • 8/6/2019 C Characters and Strings

    5/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.2 Fundamentals of Strings and

    Characters (III)

    String declarations Declare as a character array or a variable of type char *

    char color[] = "blue";

    char *colorPtr = "blue";

    Remember that strings represented as character arrays endwith '\0'

    color has 5 elements

  • 8/6/2019 C Characters and Strings

    6/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.2 Fundamentals of Strings and

    Characters (IV)

    Inputting strings Use scanf

    scanf("%s", word);

    Copies input intoword[], which does not need & (because a

    string is a pointer) Remember to leave space for'\0'

  • 8/6/2019 C Characters and Strings

    7/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.3 Character Handling Library

    Character Handling Library Includes functions to perform useful tests and manipulations

    of character data

    Each function receives a character (an int) orEOF as an

    argument

  • 8/6/2019 C Characters and Strings

    8/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.3 Character Handling Library (II)

    In

    rototype escription

    int is

    igit int c ) Returns true i c is a digit and false other ise.intisalpha(intc ) Returns true i c is a letter and false other ise.intisalnum(intc ) Returns true i c is a digit or a letter and false other ise.intisx

    igit(intc ) Returns true i c is a hexadecimal digit character and false other ise.intislower(intc ) Returns true i c is a lo ercase letter andfalse other ise.intisupper(intc ) Returns true i c is an uppercase letter; false other ise.inttolower(intc ) I c is an uppercase letter, tolower returns c as a lo ercase letter. Other ise,tolower

    returns the argument unchanged.

    inttoupper(intc ) I c is a lo ercase letter,toupper returns c as an uppercase letter. Other ise,toupperreturns the argument unchanged.

    intisspace(intc ) Returns true i c is a hite-space characterne line ('\n'), space (''), orm eed('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')and

    false other ise

    intiscntrl(intc ) Returns true i c is a control character and false other ise.intispunct(intc ) Returns true i c is a printing character other than a space, a digit, or a letter and false

    other ise.

    intisprint(intc ) Returns true value i c is a printing character including space ('') and falseother ise.

    intisgraph(intc ) Returns true i c is a printing character other than space ('') and false other ise.

  • 8/6/2019 C Characters and Strings

    9/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Load header

    2. Perform tests

    3. Print

    1 /*Fig. 8.2:fig08_02.c

    2 Usingfunctionsisdigit,isalpha,isalnum, andisxdigit*/

    3 #include

    4 #include

    5

    6 int main()

    7 {8 printf("%s\n%s%s\n%s%s\n\n","Accordingtoisdigit:",

    9 isdigit('8' ) ? "8 is a ":"8 isnot a ","digit",

    10 isdigit('#' ) ? "#is a ":

    11 "#isnot a ","digit" );

    12 printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n",

    13 "Accordingtoisalpha:",

    14 isalpha('A' ) ? "Ais a ":"Aisnot a ","letter",

    15 isalpha('b' ) ? "bis a ":"bisnot a ","letter",

    16 isalpha('&' ) ? "& is a ":"& isnot a ","letter",

    17 isalpha('4' ) ? "4 is a ":

    18 "4 isnot a ","letter" );

    19 printf("%s\n%s%s\n%s%s\n%s%s\n\n",

    20 "Accordingtoisalnum:",

    21 isalnum('A' ) ? "Ais a ":"Aisnot a ",

    22 "digitor a letter",

    23 isalnum('8' ) ? "8 is a ":"8 isnot a ",

    24 "digitor a letter",

    25 isalnum('#' ) ? "#is a ":"#isnot a ",

    26 "digitor a letter" );

    27 printf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n",

    28 "Accordingtoisxdigit:",

    29 isxdigit('F' ) ? "Fis a ":"Fisnot a ",

    30 "hexadecimal digit",

    31 isxdigit('J' ) ? "Jis a ":"Jisnot a ",

    32 "hexadecimal digit",

  • 8/6/2019 C Characters and Strings

    10/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    Program Output

    33 isxdigit('7' ) ? "7 is a ":"7 isnot a ",

    34 "hexadecimal digit",

    35 isxdigit('$' ) ? "$is a ":"$isnot a ",

    36 "hexadecimal digit",

    37 isxdigit('f' ) ? "fis a ":"fisnot a ",

    38 "hexadecimal digit" );

    39 return 0;

    40 }

    Accordingtoisdigit:

    8 is a digit#isnot a digit

    Accordingtoisalpha:Ais a letter

    bis a letter& isnot a letter4 isnot a letter

    Acc

    ording

    tois

    alnum:

    Ais a digitor a letter8 is a digitor a letter

    #isnot a digitor a letter

    Accordingtoisxdigit:

    Fis a hexadecimal digitJisnot a hexadecimal digit7 is a hexadecimal digit

    $isnot a hexadecimal digitfis a hexadecimal digit

  • 8/6/2019 C Characters and Strings

    11/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.4 String Conversion Functions

    Conversion functions In(general utilities library)

    Convert strings of digits to integer and floating-point values

    rototype escription

    doubleatof(constchar *n tr) Converts the string n tr to double.intatoi(constchar*n tr ) Converts the string n tr to int.longatol(constchar*n tr ) Converts the string n tr to long int.doublestrtod(constchar*n tr ,char**endPtr ) Converts the string nPtr to double. longstrtol(constchar*nPtr,char

    **endPtr,intbase ) Converts the string nPtr to long .

    unsignedlongstrtoul( constchar*nPtr,char**endPtr,intbase ) Converts the string nPtr to unsignedlong .

  • 8/6/2019 C Characters and Strings

    12/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variable

    2. Convert string

    2.1 Assign to variable

    3. Print

    Program Output

    1 /*Fig. 8.6:fig08_06.c

    2 Using atof*/

    3 #include

    4 #include

    5

    6 int main()7 {

    8 double d;

    9

    10 d = atof("99.0" );

    11 printf("%s%.3f\n%s%.3f\n",

    12 "Thestring\"99.0\" convertedto doubleis", d,

    13 "The convertedvalue dividedby2is",

    14 d/2.0 );

    15 return 0;

    16 }

    Thestring"99.0" convertedto doubleis99.000

    The convertedvalue dividedby2is49.500

  • 8/6/2019 C Characters and Strings

    13/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.5 Standard Input/Output Library

    Functions

    Functions in Used to manipulate character and string data

    F u n c t io n p ro t o t y p e Fu n c t io n d e sc r ip t io n

    intgetchar(v oid ); Inpu ts the nex t cha rac te r rom thes tandard inpu t and retu rns i t a s an in teger.

    char*gets(char*s ); Inpu ts cha rac te rs rom the s tandard inpu tinto the array s u ntil a ne lin e o r e nd-o -

    i le character is encountered.t e rmina t ing nu l l charac te r is append ed tothe a r ray .

    int putchar( intc ); r in ts the character s tored in c .

    intputs(constchar*s ); r in ts the s t r ing s o llo ed b y a n e lin echaracter .

    intsp rintf(char*s,constchar*format,... );

    quiva len t to p rintf , excep t the ou tpu tis s tored in the array s ins tead o

    pr int ing i t on the screen.

    intsscanf(char*s,constchar*format,... );

    quiva len t to scanf , excep t the inpu t i sread rom the a r ray s ins tead o

    read ing i t rom the keyboard .

  • 8/6/2019 C Characters and Strings

    14/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variables

    2. Input

    3. Print

    3.1 Function definition

    (note recursion)

    1 /*Fig. 8.13:fig08_13.c

    2 Usinggets andputchar */

    3 #include

    4

    5 int main()

    6 {

    7 charsentence[ 80 ];

    8 voidreverse(const char *const );

    9

    10 printf("Enter a lineoftext:\n" );

    11 gets(sentence );

    12

    13 printf("\nThelineprintedbackwardsis:\n" );

    14 reverse(sentence );

    15

    16 return 0;

    17 }

    18

    19 voidreverse(const char *const sPtr )

    20 {

    21 if (sPtr[ 0 ] == '\0' )

    22 return;

    23 else {

    24 reverse( &sPtr[ 1 ] );

    25 putchar(sPtr[ 0 ] );

    26 }

    27 }

    Enter a lineoftext:Characters and Strings

    Thelineprintedbackwardsis:

    sgnirtS dna sretcarahC

    reverse calls itself using substrings of

    the original string. When it reaches the

    '\0' character it prints usingputchar

  • 8/6/2019 C Characters and Strings

    15/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.6 String Manipulation Functions of the

    String Handling Library

    String handling library has functions to Manipulate string data

    Search strings

    Tokenize strings

    Determine string length

    Func tio n p rototype Func tio n de sc rip tio n

    char*strcpy(char*s1,constchar*s2 )

    Copies string s2 into array s1. The value o s1is

    returned.

    char*strncpy(char*s1,constchar*s2,size_tn )

    Copies at most n characters o string s2 into array

    s1. The value o s1 is returned.

    char*strcat(char*s1,constchar*s2 )

    ppends string s2 to array s1. The irst character o

    s2 over rites the terminating nullcharacter o s1.

    The value o s1 is returned.

    char*strncat(char*s1,constchar*s2,size_tn )

    ppends at most n characters o string s2 to array

    s1. The irst character o s2 over rites the

    terminating null character o s1. The value o s1 is

    returned.

  • 8/6/2019 C Characters and Strings

    16/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variables

    2. Function calls

    3. Print

    Program Output

    1 /*Fig. 8.19:fig08_19.c

    2 Usingstrcat andstrncat*/

    3 #include

    4 #include

    5

    6 int main()7 {

    8 char s1[ 20 ] = "Happy";

    9 char s2[] = "New Year ";

    10 char s3[ 40 ] = "";

    11

    12 printf("s1 = %s\ns2 = %s\n",s1,s2 );

    13 printf("strcat(s1,s2 ) = %s\n",strcat(s1,s2 ) );

    14 printf("strncat(s3,s1, 6 ) = %s\n",strncat(s3,s1, 6 ) );

    15 printf("strcat(s3,s1 ) = %s\n",strcat(s3,s1 ) );

    16 return 0;

    17 }

    s1 = Happy

    s2 = New Year

    strcat(s1,s2 ) = HappyNew Year

    strncat(s3,s1, 6 ) = Happy

    strcat(s3,s1 ) = HappyHappyNew Year

  • 8/6/2019 C Characters and Strings

    17/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.7 Comparison Functions of the String

    Handling Library

    Comparing strings Computer compares numeric ASCII codes of characters in string

    Appendix D has a list of character codes

    intstrcmp( con

    st char *

    s1, con

    st char *

    s2 );

    Compares string s1 to s2

    Returns a negative number (s1 < s2), zero (s1 == s2), or apositive number (s1 >s2)

    intstrncmp( const char *s1, const char *s2,size_tn );

    Compares up to n characters of string s1 to s2

    Returns values as above

  • 8/6/2019 C Characters and Strings

    18/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.8 Search Functions of the String

    Handling Library

    Func t i n roto t p e Func tion esc ription

    char *strchr( const char *s,int c );

    Locates the first occurrence of characterc in string s. Ifc is found, a pointer to c in

    s is returned. therwise, a NULL pointer is returned.size_tstrcspn( const char*s1, const char *s2 );

    Determines and returns the length of the initial segment of string s1 consisting of

    characters not contained in strings2.size_tstrspn( const char

    *s1, const char *s2 );Determines and returns the length of the initial segment of strin g s1 consisting only

    of characters contained in string s2.char *strpbrk( const char*s1, const char *s2 );

    Locates the first occurrence in string s1 of any character in string s2. If a character

    from string s2 is found, a pointer to the character in string s1 is returned. ther-

    wise, a NULL pointer is returned.char *strrchr( const char *s,int c );

    Locates the last occurrence ofc in string s. Ifc is found, a pointer to c in string s is

    returned. therwise, a NULL pointer is returned.char *strstr( const char *s1,

    const char *s2 );

    Locates the first occurrence in string s1 of string s2. If the string is found, a pointer

    to the string in s1 is returned. therwise, a NULL pointer is returned.char *strtok( char *s1, constchar *s2 );

    A sequence of calls to strtok breaks string s1 into tokens logical pieces such

    as words in a line of text separated by characters contained in string s2. The first

    call contains s1 as the first argument, and subsequent calls to continue tokenizing

    the same string contain NULL as the first argument. A pointer to the current token is

    returned by each call. If there are no more tokens when the function is called, NULL

    is returned.

  • 8/6/2019 C Characters and Strings

    19/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variables

    2. Function calls

    3. Print

    Program Output

    1 /*Fig. 8.27:fig08_27.c

    2 Usingstrspn*/

    3 #include

    4 #include

    5

    6 int main()

    7 {

    8 const char *string1 = "Thevalueis3.14159";

    9 const char *string2 = "aehilsTuv";

    10

    11 printf("%s%s\n%s%s\n\n%s\n%s%u\n",

    12 "string1 = ",string1,"string2 = ",string2,

    13 "Thelength oftheinitialsegmentofstring1",

    14 "containingonly charactersfromstring2 = ",

    15 strspn(string1,string2 ) );

    16 return 0;

    17 }

    string1 = Thevalueis3.14159

    string2 = aehilsTuv

    Thelength oftheinitialsegmentofstring1containingonly charactersfromstring2 = 13

  • 8/6/2019 C Characters and Strings

    20/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variables

    2. Function calls

    3. Print

    Program Output

    1 /*Fig. 8.29:fig08_29.c

    2 Usingstrtok */

    3 #include

    4 #include

    5

    6 int main()

    7 {

    8 char string[] = "Thisis a sentence with 7 tokens";

    9 char *tokenPtr;

    10

    11 printf("%s\n%s\n\n%s\n",

    12 "Thestringtobetokenizedis:",string,

    13 "Thetokens are:" );

    14

    15 tokenPtr = strtok(string,"" );

    1617 while (tokenPtr != NULL ) {

    18 printf("%s\n",tokenPtr );

    19 tokenPtr = strtok(NULL,"" );

    20 }

    21

    22 return 0;

    23 }

    Thestringtobetokenizedis:Thisis a sentence with 7 tokens

    Thetokens are:Thisis

    a

    sentencewith

    7tokens

  • 8/6/2019 C Characters and Strings

    21/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.9 Memory Functions of the String-

    handling Library

    Memory Functions

    In

    Manipulate, compare, and search blocks of memory

    Can manipulate any block of data

    Pointer parameters are void*

    Any pointer can be assigned to void*, and vice versa

    void* cannot be dereferenced

    Each function receives a size argument specifying the numberof bytes (characters) to process

  • 8/6/2019 C Characters and Strings

    22/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.9 Memory Functions of the String-

    handling Library (II)

    Prototype escription

    void*memcpy(void*s1,constvoid*s2,size_tn )

    Copies n characters rom the object pointed to bys2 into the object

    pointed to by s1. pointer to the resulting object is returned.

    void*memmove(void*s1,constvoid*s2,

    size_tn )

    Copies n characters rom the object pointed to bys2 into the object

    pointed to by s1. The copy is per ormed as i the characters are irstcopied rom the object pointed to bys2 into a temporary array, and

    then copied rom the temporary array into the object pointed to bys1. pointer to the resulting object is returned.

    intmemcmp(constvoid*s1,constvoid*s2,size_tn )

    Compares the irstn characters o the objects pointed to bys1 and

    s2. The unction returns0, less than 0, or greater than 0 i s1 is

    equal to, less than or greater thans2, respectively.void*memchr(constvoid*s,intc,size_t

    n )

    Locates the irst occurrence o c (converted to unsignedchar) in

    the irst n characters o the object pointed to bys. I c is ound, apointer to c in the object is returned. Other ise,0 is returned.

    void*memset(void*s,intc,size_tn ) Copies c (converted to unsignedchar) into the irstn characterso the object pointed to bys. pointer to the result is returned.

    " b ect" refers to a block of data

  • 8/6/2019 C Characters and Strings

    23/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Initialize variables

    2. Function calls

    3. Print

    Program Output

    1 /*Fig. 8.32:fig08_32.c

    2 Usingmemmove*/

    3 #include

    4 #include

    5

    6 int main()

    7 {

    8 char x[] = "Home SweetHome";

    9

    10 printf("%s%s\n",

    11 "Thestringin arrayxbeforememmoveis:",x );

    12 printf("%s%s\n",

    13 "Thestringin arrayx after memmoveis: ",

    14 memmove(x, &x[ 5 ],10 ) );

    15

    16 return 0;

    17 }

    Thestringin arrayxbeforememmoveis:Home SweetHomeThestringin arrayx after memmoveis: SweetHomeHome

  • 8/6/2019 C Characters and Strings

    24/25

    2000 Prentice Hall, Inc. All rights reserved.

    8.10 Other Functions of the String Handling

    Library

    char *strerror(interrornum );

    Creates a system-dependent error message based on errornum

    Returns a pointer to the string

    size_tstrlen( const char *s );

    Returns the number of characters (before NULL) in string s

  • 8/6/2019 C Characters and Strings

    25/25

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. Function call

    2. Print

    Program Output

    1 /*Fig. 8.37:fig08_37.c

    2 Usingstrerror */

    3 #include

    4 #include

    5

    6 int main()

    7 {

    8 printf("%s\n",strerror(2 ) );

    9 return 0;

    10 }

    Nosuch fileor directory