Using Character Strings

A more complex version of characters is the character string. Unlike strings you might have used in other programming languages, character strings are a sequence of individual characters.

The easiest way to create a character string is

char name[] = "David Brent";

This will create a variable called name, which contains the string David Brent. However, because character strings must end with the character (which is the NULL character), name actually contains 12 characters.

Chapter 11 will discuss strings in all their glory. In the meantime, let's quickly add and print a character string in our working example.

To work with character strings

1.
Open var4.c (Script 2.4) in your text editor or IDE.

2.
After declaring the other three variables, declare and initialize a character string called name (Script 2.5):

char name[] = "Franny Isabel";

Script 2.5. Characters variables can be used to create longer strings, like name here.


3.
Add a fourth print statement for this new variable:

printf ("Your name is %s.
", name);

Since the name variable is a character string, you'll need to use the %s signifier within the printf() function.

4.
Save the file as var5.c.

5.
Compile and run the application (Figure 2.6).

Figure 2.6. Here a character string representing a person's name is printed out along with the other variables.


✓ Tip

  • The character string is actually an array of characters. You'll learn more about arrays in general (and use many more character arrays) in Chapter 6, “Working with Arrays.”


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset