120 likes | 251 Views
Strings. Includes: #include <stdio.h> #include <stdlib.h> /* needed by atoi( ) and atof( ) */ #include <string.h> /* needed by str...( ) functions */. Copy One Array to Another. /* assign a to b */ strcpy( b, a ); printf( "%s<br>", b );. Add One Array to Another.
E N D
Strings Includes: • #include <stdio.h> • #include <stdlib.h> /* needed by atoi( ) and atof( ) */ • #include <string.h> /* needed by str...( ) functions */
Copy One Array to Another • /* assign a to b */ • strcpy( b, a ); • printf( "%s\n", b );
Add One Array to Another • strcpy( b, a ); • strcat ( b, " " ); • strcat ( b, a );
Compare Strings • /* "Gary Burt" comes before "Mike Burt", so print a negative number */ • printf( "%d\n", strcmp( a, c ) ); • /* "Mike Burt" comes before "Gary Burt", so print a positive number */ • printf( "%d\n", strcmp( c, a ) ); • /* "Gary Burt" is the same as "Gary Burt", so print zero */ • printf( "%d\n", strcmp( a, "Gary Burt" ) );
Getting Words From a String • /* get the first token (delimited by a blank) */ • printf( "%s\n", strtok( b, " " ) );
Convert String to Numeric • /* convert a string to an integer */ • printf( "%d\n", atoi( "1234" ) ); • /* convert a string to a float */ • printf( "%f\n", atof( "1234.5678" ) );
Find Length Of A String • printf( "b is %d characters long\n", strlen( b ) );
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( "%s\n", a );
Sample Program • /* assign a to b */ • strcpy( b, a ); • printf( "%s\n", b ); • /* put in a space and add the array a to what is in array a */ • printf( "b is %d characters long\n", strlen( b ) ); • printf( "%s\n", b ); • strcat ( b, " " ); • printf( "b is %d characters long\n", strlen( b ) ); • printf( "%s\n", b ); • strcat ( b, a ); • printf( "b is %d characters long\n", strlen( b ) ); • printf( "%s\n", b );
Sample Program • /* "Gary Burt" comes before "Mike Burt", so print a negative number */ • printf( "%d\n", strcmp( a, c ) ); • /* "Mike Burt" comes before "Gary Burt", so print a positive number */ • printf( "%d\n", strcmp( c, a ) ); • /* "Gary Burt" is the same as "Gary Burt", so print zero */ • printf( "%d\n", strcmp( a, "Gary Burt" ) ); • /* get the first token (delimited by a blank) */ • printf( "%s\n", strtok( b, " " ) );
Sample Program • /* convert a string to an integer */ • printf( "%d\n", atoi( "1234" ) ); • /* convert a string to a float */ • printf( "%f\n", atof( "1234.5678" ) ); • return 0; • }
Output • Gary Burt • Gary Burt • b is 9 characters long • Gary Burt • b is 10 characters long • Gary Burt • b is 19 characters long • Gary Burt Gary Burt • -1 • 1 • 0 • Gary • 1234 • 1234.567800