ProgrammerGuide.Net | Step by Step Programmer Guide

C-Character Array and String

Character Array and String,

INTRODUCTION
A string is a sequence of characters that is treated as a single data item. We have used strings in a number of examples in a number of example in the past. Any group of characters(except double quote sign) defined between double quotation marks is a string constant. Example:
“Man is obviously made to think.”

If we want to include a double quote in the string to be printed, then we may use it with a back slash as shown below.
“\” Man is obviously made to think,\” said Pascal.”

For example,
        printf (“\” Well Done !”\”);

will output the string

        ” Well Done !”

While the statement

        printf (” Well Done !”);

will output the string

        Well  Done!
Character  strings are often used to build meaningful and readable programs. The common operations performed on character string include:

1. Reading and writing strings
2. Combining string together
3. Copying one string to another
4. Comparing string for equality
5. Extracting a portion of a string
In this chapter we shall discuss these operations in detail and examine library function that implement them.

DECLARING AND INITIALIZING STRING VARIABLE
C does not support strings as a data type. However, it allows us to represent string as character arrays. in c therefore, a string variable is any validc variable name and is always declaredas an array of characters. The general form of declaration of a string variable is.

char string_name[ size ];

The size determine the number of characters in the string…. name. Some examples are:

char city[10];

char name[30];

Like numeric arrays, character arrays may be initialized when they are declared C permits a character array to be initialized in either of the following two forms

char city [9] = ” NEW YORK “;

char city [9] = {‘ N ‘,’ E ‘,’ W ‘,’  ‘ ,’ Y ‘,’ O ‘,’ R ‘,’ K ‘};

This will result in a compile time error. Also note that we cannot separate the initialization from declaration. This is

char str3[5];

str3 = “GOOD”;

is not allowed. Similarly,

char s1[4] = “abc”;

char s2[4];

s2 = s1; /* Error //
is not allowed. An array name cannot be used as the left operand of an assignment operator.

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?