Strings
Strings
Strings
Stings in C are stored as null character, '\0', terminated character arrays. This means
that the length of a string is the number of characters it contains plus one to store
the null character. Common string operations include finding lengths, copying,
searching, replacing and counting the occurrences of specific characters and words.
Here is a simple way to determine the length of a string.
#include <stdio.h>
int main()
{
char sentence[] = "Hello World";
int count = 0;
int i;
return 0;
}
Each character within the array sentence is compared with the null character
terminator until the end of the string is encountered. This technique can be
generalized to search for any character.
#include <stdio.h>
int main()
{
int i,j;
char buffer[120]; /* Holds input strings */
char *pt; /* A pointer to data type char */
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int alphaCount[26]; /* an array of counts */
/* Initialize counts */
for (i = 0; i < 26; i++)
{
alphaCount[i] = 0;
}
return 0;
}
gets reads a line of input into a character array. Its prototype is:
char *gets(char *buffer);
The first step in this program is to initialize the count array. When you use an
automatic variable, you must initialize it. Otherwise, it contains whatever data
happened to be at the memory location it is stored in. This will be discussed further
in the lesson on variable scope.
The while loop in this program reads lines of input until an end of file is encountered.
If you run this program, remember that an end of file, EOF, is entered as a control-d
or a control-z from you keyboard. This is, after you type the last line of text, type
control-z or control-d to enter the End of File character.
For each line read in, each character in the line is compared against each letter in the
alphabet. If a match is found the appropriate count is incremented. The last step in
this program writes out the results.
Practice:
1) Type in the above program. Compile and run.
2) Modify the above program to count the occurrences of the digits 0-9, rather than
letters.
Solution
#include <stdio.h>
int main()
{
int i,j;
char buffer[120]; /* Holds input strings */
char *pt; /* A pointer to data type char */
char digits[11] = "0123456789";
int digitCount[10]; /* an array of counts */
/*Initialize counts */
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
return 0;
}
Let's look at an example of using fgets, and then we'll talk about some pitfalls to watch out for.
For a example:
#include <stdio.h>
int main()
{
/* A nice long string */
char string[256];
getchar();
}
Remember that you are actually passing the address of the array when you pass string because
arrays do not require an address operator (&) to be used to pass their addresses, so the values in
the array string are modified.
The one thing to watch out for when using fgets is that it will include the newline character ('\n')
when it reads input unless there isn't room in the string to store it. This means that you may need
to manually remove the input. One way to do this would be to search the string for a newline and
then replace it with the null terminator. What would this look like? See if you can figure out a way to
do it before looking below:
char input[256];
int i;
Here, we just loop through the input until we come to a newline, and when we do, we replace it with
the null terminator. Notice that if the input is less than 256 characters long, the user must have hit
enter, which would have included the newline character in the string! (By the way, aside from this
example, there are other approaches to solving this problem that use functions from string.h.)
/* this function is designed to remove the newline from the end of a string
entered using fgets. Note that since we make this into its own function, we
could easily choose a better technique for removing the newline. Aren't
functions great? */
void strip_newline( char *str, int size )
{
int i;
int main()
{
char name[50];
char lastname[50];
char fullname[100]; /* Big enough to hold both name and lastname */
printf( "Please enter your name: " );
fgets( name, 50, stdin );
getchar();
return 0;
}
strcpy
strcpy copies a string, including the null character terminator from the source string
to the destination. This function returns a pointer to the destination string, or a NULL
pointer on error. Its prototype is:
strncpy
strncpy is similar to strcpy, but it allows the number of characters to be copied to be
specified. If the source is shorter than the destination, than the destination is padded
with null characters up to the length specified. This function returns a pointer to the
destination string, or a NULL pointer on error. Its prototype is:
strcat
This function appends a source string to the end of a destination string. This function
returns a pointer to the destination string, or a NULL pointer on error. Its prototype
is:
strncat
This function appends at most N characters from the source string to the end of the
destination string. This function returns a pointer to the destination string, or a NULL
pointer on error. Its prototype is:
strcmp
This function compares two strings. If the first string is greater than the second, it
returns a number greater than zero. If the second string is greater, it returns a
number less than zero. If the strings are equal, it returns 0. Its prototype is:
strncmp
This function compares the first N characters of each string. If the first string is
greater than the second, it returns a number greater than zero. If the second string
is greater, it returns a number less than zero. If the strings are equal, it returns 0.
Its prototype is:
strlen
This function returns the length of a string, not counting the null character at the
end. That is, it returns the character count of the string, without the terminator. Its
prototype is:
memset
memset is useful to initialize a string to all nulls, or to any character. It sets the first
N positions of the sting to the value passed. The destination may be specified by a
pointer to any type, char, int, float, etc. A void pointer is used to allow different types
to be specified. Its prototype is:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
char str3[20];
char *cpt;
int length;
int rc;
/* Clear str3 */
memset(str3,'\0',20);
printf("\nstr3 is cleared\n");
return 0;
}
In this example error checking on the library calls was not done in order to simplify
the presentation. As an example, only the first call was checked.
int main()
{
int i,j;
char buffer[120]; /* Holds input strings */
char *pt; /* A pointer to data type char */
char digits[11] = "0123456789";
int digitCount[10]; /* an array of counts */
/*Initialize counts */
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
return 0;
}Here is a simple program to illustrate the use of some of these functions.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
char str3[20];
char *cpt;
int length;
int rc;
/* Clear str3 */
memset(str3,'\0',20);
printf("\nstr3 is cleared\n");
return 0;
}
In this example error checking on the library calls was not done in order to simplify
the presentation. As an example, only the first call was checked.
#include <stdio.h>
int main()
{
int i,j;
char buffer[120]; /* Holds input strings */
char *pt; /* A pointer to data type char */
char digits[11] = "0123456789";
int digitCount[10]; /* an array of counts */
/*Initialize counts */
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
return 0;
}
int main()
{
int i,j;
char buffer[120]; /* Holds input strings */
char *pt; /* A pointer to data type char */
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int alphaCount[26]; /* an array of counts */
/* Initialize counts */
for (i = 0; i < 26; i++)
{
alphaCount[i] = 0;
}
return 0;
}
gets reads a line of input into a character array. Its prototype is:
char *gets(char *buffer);
The while loop in this program reads lines of input until an end of file is encountered.
If you run this program, remember that an end of file, EOF, is entered as a control-d
or a control-z from you keyboard. This is, after you type the last line of text, type
control-z or control-d to enter the End of File character.
For each line read in, each character in the line is compared against each letter in the
alphabet. If a match is found the appropriate count is incremented. The last step in
this program writes out the results.
Using Strings
Strings are useful for holding all types of long input. If you want the user to input his or her name,
you must use a string. Using scanf() to input a string works, but it will terminate the string after it
reads the first space, and moreover, because scanf doesn't know how big the array is, it can lead to
"buffer overflows" when the user inputs a string that is longer than the size of the string (which acts
as an input "buffer").
There are several approaches to handling this problem, but probably the simplest and safest is to
use the fgets function, which is declared in stdio.h.
When fgets actually reads input from the user, it will read up to size - 1 characters and then place
the null terminator after the last character it read. fgets will read input until it either has no more
room to store the data or until the user hits enter. Notice that fgets may fill up the entire space
allocated for str, but it will never return a non-null terminated string to you.
Let's look at an example of using fgets, and then we'll talk about some pitfalls to watch out for.
For a example:
#include <stdio.h>
int main()
{
/* A nice long string */
char string[256];
getchar();
}
Remember that you are actually passing the address of the array when you pass string because
arrays do not require an address operator (&) to be used to pass their addresses, so the values in
the array string are modified.
The one thing to watch out for when using fgets is that it will include the newline character ('\n')
when it reads input unless there isn't room in the string to store it. This means that you may need
to manually remove the input. One way to do this would be to search the string for a newline and
then replace it with the null terminator. What would this look like? See if you can figure out a way to
do it before looking below:
char input[256];
int i;
Here, we just loop through the input until we come to a newline, and when we do, we replace it with
the null terminator. Notice that if the input is less than 256 characters long, the user must have hit
enter, which would have included the newline character in the string! (By the way, aside from this
example, there are other approaches to solving this problem that use functions from string.h.)
To obtain a line of text from the user via the keyboard, there are a few standard functions
available. These include:
char *fgets(char *s, int size, FILE *stream);
int scanf( const char *format, ...);
char *gets(char *s);
The first on the list, fgets(), it the best function to use, as it provides control over how many
characters are actually read into memory. The scanf() function can be used to do this too, but
it is really designed for use with formatted input. By this I mean a data stream that is in a
guaranteed format, which is something a user with a keyboard can rarely provide with any
accuracy The gets() function is old, and should not be used. It doesn't control the number of
characters it reads in, and will happily overwrite memory it doesn't own if the user provides an
unexpectedly long line of input.
fgets() reads in at most one less than size characters from stream and stores them into the
buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is
stored into the buffer. A '\0' is stored after the last character in the buffer.
One problem that people find with fgets(), is that it may place the newline character \n
([Enter]) into the buffer. That is, if there is enough room to store the newline in the array, it
will. This can cause problems with string comparisons, file names, and a number of other
things you use your input for. An example of this problem would be passing the array to the
fopen() function to open a file stream. The newline character would be taken as part of the file
name itself, and the operating system would look for a file named myfile.dat\n. Of course,
when debugging, it can be easy to miss this, as the variable contents is printed normally on
the screen.
Here is an example of how to use fgets(). It shows how to remove the newline from the end of
the array. Remember, it is important to check for the existence of this character before wiping
it out with a \0, as it is not always there.
Note the position of the < and > signs in the output. These help show the presence of the
newline character in the buffer.
#include <stdio.h>
#include <string.h>
int main()
{
char buf[BUFSIZ];
char *p;
printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
printf ("Thank you, you entered >%s<\n", buf);
/*
* Now test for, and remove that newline character
*/
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
printf ("And now it's >%s<\n", buf);
}
return 0;
}
/*
Program output:
Please enter a line of text, max 512 characters
this is a test
Thank you, you entered >this is a test
<
And now it's >this is a test<
*/
/*
* This code is written in C, but it could just as easily be done in C++.
* The rand() and srand() functions are available in both languages.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i;
srand(time(NULL));
i = rand();
printf ("Your random number is %d\n", i);
printf ("This compiler can generate random numbers from 0 to %d\n", RAND_MAX);
return(0);
}
#include <stdio.h>
#include <string.h>
int main()
{
char buf[BUFSIZ];
char *p;
printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
printf ("Thank you, you entered >%s<\n", buf);
/*
* Now test for, and remove that newline character
*/
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
printf ("And now it's >%s<\n", buf);
}
return 0;
}
/*
Program output:
Please enter a line of text, max 512 characters
this is a test
Thank you, you entered >this is a test
<
And now it's >this is a test<
*/
This is system dependent as the most portable solution relies on the keyboard codes that map
to the directional keys. Next you need a raw input function that takes a single character such
as getch (a UNIX implementation is given later in this FAQ "How can I get input without
having the user hit [Enter]?"). To get the correct codes for your system, you must search by
way of a simple input function:
int get_code ( void )
{
int ch = getch();
if ( ch == 0 || ch == 224 )
ch = 256 + getch();
return ch;
}
Then build a list of key code constants so that they can be easily changed if the program is
ported:
enum
{
KEY_UP = 256 + 72,
KEY_DOWN = 256 + 80,
KEY_LEFT = 256 + 75,
KEY_RIGHT = 256 + 77
};
Then it is only a matter of testing for those codes in your program and performing the correct
action:
#include <stdio.h>
#include <conio.h>
/* System dependent key codes */
enum
{
KEY_ESC = 27,
ARROW_UP = 256 + 72,
ARROW_DOWN = 256 + 80,
ARROW_LEFT = 256 + 75,
ARROW_RIGHT = 256 + 77
};
static int get_code ( void )
{
int ch = getch();
if ( ch == 0 || ch == 224 )
ch = 256 + getch();
return ch;
}
int main ( void )
{
int ch;
while ( ( ch = get_code() ) != KEY_ESC ) {
switch ( ch ) {
case ARROW_UP:
printf ( "UP\n" );
break;
case ARROW_DOWN:
printf ( "DOWN\n" );
break;
case ARROW_LEFT:
printf ( "LEFT\n" );
break;
case ARROW_RIGHT:
printf ( "RIGHT\n" );
break;
}
}
return 0;
}
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <windows.h>
int main ( void )
{
short esc = 0;
while ( !esc ) {
esc = GetAsyncKeyState ( VK_ESCAPE );
if ( GetAsyncKeyState ( VK_UP ) & SHRT_MAX )
puts ( "Up arrow is pressed" );
else if ( GetAsyncKeyState ( VK_DOWN ) & SHRT_MAX )
puts ( "Down arrow is pressed" );
else if ( GetAsyncKeyState ( VK_LEFT ) & SHRT_MAX )
puts ( "Left arrow is pressed" );
else if ( GetAsyncKeyState ( VK_RIGHT ) & SHRT_MAX )
puts ( "Right arrow is pressed" );
}
return EXIT_SUCCESS;
}