Lesson 10: Strings
This lesson will show you how to:
- what are strings?
- assigning strings to variables
- use of the strcpy() function
- use of the string.h header file
Q: Why didn't the blonde want a window seat on the plane?
A: She'd just blow dried her hair and she didn't want it
blown around too much.
Some basic ways to analyze and manipulate string data
and then presents some C library functions that are useful
for string manipulation. Character data is stored using
thedata type "char". String data is stored as
a null character terminated character array.
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.
char sentence = "Hello World";
int count = 0, i;
for (i = 0; sentence[i] != '\0';
printf("The string %s has %d
printf("and is stored in %d
Each character within the array sentence is compared with
the null character terminator until the end of the string
is encountered. You can use this technique to search for
any chracter in any string.
Library Functions for String Manipulation
To use any of these functions in your code, the header file
"strings.h" must be included. It is the programmer's
responsibility to check that the destination array is large
enough to hold either what is copied or appended to it.
C performs no error checking in this respect.
strcpy copies a string, including the null character terminator
from the source string to the destination. You must attach
the string.h header file to use this function. This is the
only function from that library that i want you to know
for now, the remaining functions in that library are not
that important nor useful. Its prototype is:
ariable is the variable (now known as a string literal)
that the string will be assigned to, string is the actual
string that you are assigning to the variable.
const char yes = ‘y’
char garment = “overcoat”;
printf(“Is it raining outside?
Answer y/n \n”);
if (reply == yes)
printf(“before you go out
today take your %s\n”, garment);
back to top go
to next lesson