Strings Includes include stdio h include stdlib h
Strings Includes: • #include <stdio. h> • #include <stdlib. h> /* needed by atoi( ) and atof( ) */ • #include <string. h> /* needed by str. . . ( ) functions */ CMSC 104, Version 9/01 1
Copy One Array to Another • /* assign a to b */ • strcpy( b, a ); • printf( "%sn", b ); CMSC 104, Version 9/01 2
Add One Array to Another • strcpy( b, a ); • strcat ( b, " " ); • strcat ( b, a ); CMSC 104, Version 9/01 3
Compare Strings • /* "Gary Burt" comes before "Mike Burt", so print a negative number */ • printf( "%dn", strcmp( a, c ) ); • /* "Mike Burt" comes before "Gary Burt", so print a positive number */ • printf( "%dn", strcmp( c, a ) ); • /* "Gary Burt" is the same as "Gary Burt", so print zero */ • printf( "%dn", strcmp( a, "Gary Burt" ) ); CMSC 104, Version 9/01 4
Getting Words From a String • /* get the first token (delimited by a blank) */ • printf( "%sn", strtok( b, " " ) ); CMSC 104, Version 9/01 5
Convert String to Numeric • /* convert a string to an integer */ • printf( "%dn", atoi( "1234" ) ); • /* convert a string to a float */ • printf( "%fn", atof( "1234. 5678" ) ); CMSC 104, Version 9/01 6
Find Length Of A String • printf( "b is %d characters longn", strlen( b ) ); CMSC 104, Version 9/01 7
Sample Program • • • #include <stdio. h> #include <stdlib. h> /* needed by atoi( ) and atof( ) */ #include <string. h> /* needed by str. . . ( ) functions */ • • • int main( void ) { char a[ 100 ] = "Gary Burt"; char b[ 100 ]; char c[ 100 ] = "Mike Burt"; • • /* Make sure the array a is as expected */ printf( "%sn", a ); • CMSC 104, Version 9/01 8
Sample Program • • • /* assign a to b */ strcpy( b, a ); printf( "%sn", b ); /* put in a space and add the array a to what is in array a */ printf( "b is %d characters longn", strlen( b ) ); printf( "%sn", b ); strcat ( b, " " ); printf( "b is %d characters longn", strlen( b ) ); printf( "%sn", b ); strcat ( b, a ); printf( "b is %d characters longn", strlen( b ) ); printf( "%sn", b ); • CMSC 104, Version 9/01 9
Sample Program • • /* "Gary Burt" comes before "Mike Burt", so print a negative number */ printf( "%dn", strcmp( a, c ) ); • /* "Mike Burt" comes before "Gary Burt", so print a positive number */ • printf( "%dn", strcmp( c, a ) ); • • /* "Gary Burt" is the same as "Gary Burt", so print zero */ printf( "%dn", strcmp( a, "Gary Burt" ) ); • • /* get the first token (delimited by a blank) */ printf( "%sn", strtok( b, " " ) ); • CMSC 104, Version 9/01 10
Sample Program • /* convert a string to an integer */ • printf( "%dn", atoi( "1234" ) ); • • /* convert a string to a float */ printf( "%fn", atof( "1234. 5678" ) ); • return 0; • } CMSC 104, Version 9/01 11
Output • • • • Gary Burt b is 9 characters long Gary Burt b is 10 characters long Gary Burt b is 19 characters long Gary Burt -1 1 0 Gary 1234. 567800 CMSC 104, Version 9/01 12
- Slides: 12