Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings #include <stdio.h>

Similar presentations


Presentation on theme: "Strings #include <stdio.h>"— Presentation transcript:

1 Strings #include <stdio.h>
#include <stdlib.h> /* needed by atoi( ) and atof( ) */ #include <string.h> /* needed by str...( ) functions */

2 Copy One Array to Another
/* assign a to b */ strcpy( b, a ); printf( "%s\n", b );

3 Add One Array to Another
strcpy( b, a ); strcat ( b, " " ); strcat ( b, a );

4 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" ) );

5 Getting Words From a String
/* get the first token (delimited by a blank) */ printf( "%s\n", strtok( b, " " ) );

6 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( " " ) );

7 Find Length Of A String printf( "b is %d characters long\n", strlen( b ) );

8 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 );

9 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 ) ); strcat ( b, " " ); strcat ( b, a );

10 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, " " ) );

11 /* convert a string to an integer */ printf( "%d\n", atoi( "1234" ) );
Sample Program /* convert a string to an integer */ printf( "%d\n", atoi( "1234" ) ); /* convert a string to a float */ printf( "%f\n", atof( " " ) ); return 0; }

12 Output Gary Burt b is 9 characters long b is 10 characters long
Gary Burt Gary Burt -1 1 Gary 1234


Download ppt "Strings #include <stdio.h>"

Similar presentations


Ads by Google