Strings

 

The most familiar use of one-dimensional character array is the  ‘string’. A string is defined by a character array terminated by a NULL character. And this NULL character is represented by a ‘\0’. Here you should not confuse between the  ‘\0’ and  ‘0’ character. That character sequence ‘\0’ is not treated as two characters, rather than it is treated as a single character, known as a NULL character. And another distinguished feature is that the ASCII value of NULL character is 0 whereas the ASCII value of 0 is 48.

Thus when we are going to initialize a string, then it becomes necessary to insert the NULL character at the end of the string as shown below:

char name[6] = {‘L’, ‘o’, ‘h’, ‘i’, ‘t’, ‘\0’};

 

Now look at the earlier initialization and this later initialization. In earlier initialization we did not insert a NULL (\0) character, so it is a simple an array of chars, whereas in later initialization we have inserted a NULL (\0) character at the end, therefore it is not just a simple array of char, rather it can be treated as a string.

Basically there are two ways of initializing a string:

char name[6] = {‘L’, ‘o’, ‘h’, ‘i’, ‘t’, ‘\0’};

char name[6] = “Lohit”  ;

 

In earlier initialization (first one) of these strings, we are storing the characters individually and therefore it is essential to insert a NULL character at the end, whereas in later case (second one) the null character is inserted automatically by the compiler. One main point to remember that while declaring an array of char as a string then the size of string should be declared one character longer. It means that if an array of chars can hold 6 characters then it can store 5 characters as a string because last character stored in the string is a NULL character. On the other hand, if we want to store only characters then it can store 5 characters.

Now we will see how to display the output of strings. In first method we just write the print statement as we have used earlier i.e.

 

/* Program – st.c */

#include

main()

{ char name[6] = “Lohit”;

int counter;

for (counter = 0; counter <6; counter++)

printf(“%c”, name[counter]);

}

 

The output of this program is as….

Lohit

The limitation of this program is that programmer has to mention the length of the string in his program. One may ask - Is there any other option to find the end of the string? Its answer is yes. And here introduces the advantage of associating a NULL (\0) character at the end of the string. Even if we do not know the number of character in a string, but we can easily traverse from one character to next until a NULL character appears.

 

Following program illustrates this concept clearer:

 

/* Program – st1.c */

#include

main()

{

char name1[] = "Adam";

char name2[] = "Gilchrist";

int counter;

printf("\nThis output has come without a NULL character.");

for(counter=0; counter<4; counter++)

printf("%c",name1[counter]);

printf("\nThis output has come with the help of a NULL character."):

for(counter=0; name2[counter] != '\0'; counter++)

printf("%c", name2[counter]);

}

 

 

The output of this program is as….

This output has come without a NULL character.

Adam

This output has come with the help of a NULL character.

Gilchrist

In this program we have used two loops. First loop uses number of characters stored in the array and it ends when the counter variable ‘i’ becomes 4. Second loop continues until the  ‘\0’ character appears in the variable name2[i]. Because we all know that each string is always ended by the ‘\0’ (NULL) character. Now you may better understand the use of NULL character.

In above program we have accessed the elements of character array one by one. Fortunately C provides a better way to access the complete string simultaneously by providing a format specifier %s in the format string. We all know that

 

 %d is used for integer

%f is used for float and

%c is used for character variables

 

 

Similarly

%s

is used for strings.

 

Following program illustrates this concept.

 

/* Program - st2.c */

#include

main()

{

char name1[] = "Adam";

char name2[] = "Gilchrist";

printf("\nFirst name : %s", name1);

printf("\nSecond name : %s", name2);

}

 

The output of this program is as….

First name : Adam

Second name : Gilchrist

Similarly we can also receive a string from the keyboard by using %s as format specifier in strong format of  scanf() as depicts in following program:

/* Program - st3.c */

#include

main()

{ char name1[15], name2[15];

printf("\nEnter first name : ");

scanf("%s", name1);

printf("Enter second name : ");

scanf("%s", name2);

printf("\nFirst name : %s", name1);

printf("\nSecond name : %s", name2);

}

The output of this program is as….

Enter first name : Atishrestha

Enter second name : Sagar

First name : Atishrestha

Second name : Sagar

The first limitation of using ‘%s’ in format specifier is that the programmer has to keep in mind about the size of character array. It means that if you are declaring 15 as a size of array char then you can not store more than 15 characters into it. If you have stored more than 15 characters then the result would be unpredictable because upto 15 there is no problem, but after this if you just type another character then it may overlap over some other important information and thus it may lead to disastrous result. So be care full when you are receiving strings from the keyboard.

Another limitation with the receiving of strings from keyboard is that you can not receive multi words string from the keyboard through scanf () statement. What should you expect the output of the following program?

/* Program - st4.c */

#include

main()

{

char name[20];

printf("\nEnter your name : ");

scanf("%s", name);

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

}

 

The output of this program is as….

Enter your name : Nikita Sagar

Your name is Nikita.

From the output of this program it is clear that if you type Nikita Sagar then only the first word ‘Nikita’ would be stored in string name2. It happens so because after typing ‘Nikita’ when you typed ‘Sagar’ just after one or more spaces then it would automatically terminate the string. That’s why we receive only first word ‘Nikita’.

Fortunately C also provides a standard function gets() to receive multiword strings from keyboard and puts() to print multiword strings on the screen.

Following program illustrates this concept:

/* Program - st5.c */

#include

main()

{ char  name1[15], name2[15];

printf(“\nEnter the name of first user : ”);  

gets(user1);

printf(“\nEnter the name of second user : ”);  

gets(user2);

printf(“\nFirst user name : ");

puts(user1);

printf(“\nSecond user name : ”);

puts(user2);

}

 

The output of this program is as….

Enter the name of first user : Steve Waugh

Enter the name of second user : Mark Waugh

First user name : Steve Waugh

Second user name : Mark Waugh

In this program we have used two built-in functions gets () and puts () to receive and display the multi words string respectively. But these functions are not without limitation. The main limitation is that we can receive only and only one string by using function gets () and similarly we can display only one string at a time. It means that following statements are absolutely invalid:

gets (name1, name2);

puts (name1, name2);

 

Like

 printf() function, in puts()

function we can also display the string constant on the screen.

Now let us write a simple string program that converts an uppercase string into lower case string. That is if you entered following string

HOW ARE YOU?

You program should display following string

how are you?

We know that the ASCII value of uppercase letters (A, B, C,…. X, Y and Z) come between 65 and 90 and the ASCII value of lower case letters  (a, b, c,….x, y and z) falls between 97 to 122. The difference between the each uppercase letter and its corresponding lowercase letter is of 32.

Following program uses this difference to convert uppercase letters to lowercase:

/* Program - st6.c */

#include

main()

{ char name[40];

int i =0;

puts("\nEnter any upper case string : ");

gets(name);

puts("You have entered this upper case string : ");

puts(name);

while (name[i] != '\0')

{

if ((name[i] >=65) && (name[i] <=90))

name[i] = name[i]+32 ;

i++ ;

}

puts("\nChanged lower case string : ");

puts(name);

}

 

The output of this program is as….

Enter any upper case string : HOW  ARE YOU?

You have entered this upper case string : HOW  ARE YOU?

Changed lower case string : how are you?

You can try yourself another program that converts a lowercase string into an uppercase  string.

 

Array of Strings

Array of strings is also known as two-dimensional array of characters. The declaration of two-dimensional array of characters is as:

char array-name[row][col] ;

Here array_name is the name of a two-dimensional array of strings, row contains number of strings and col contains the number of columns reserved for each string.

For example, consider the following declaration

char days[7][10];

Here days is the name of array having 7 strings (or rows) and 10 is the number of columns reserved for each string (row).

We can also initialize the array of strings during its declaration as:

char days[7][10] =  {

{‘M’, ‘O’, ‘N’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘T’, ‘U’, ‘E’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘W’, ‘E’, ‘D’, ‘N’, ‘E’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘T’, ‘H’, ‘R’, ‘U’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘F’, ‘R’, ‘I’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘S’, ‘A’, ‘T’, ‘U’, ‘R’, ‘D’, ‘A’, ‘Y’, ‘\0’},

{‘S’, ‘U’, ‘N’, ‘D’, ‘A’, ‘Y’, ‘\0’}

};

 

Another way of initializing the array of strings is as:

char days[7][10] =  {

“MONDAY”,

“TUESDAY”,

“WEDNESDAY”,

“THRUSDAY”,

“FRIDAY”,

“SATURDAY”,

“SUNDAY”

};

 

Naturally the later initialization is more easily understandable for the C lovers.

If we want to display the contents of array of strings named days [][] then we will use the following statement:

for (i=0; i<=6 ; i++)

printf (“\n %s”,days[i]);

 

You can also use the following statement to display the contents of array of strings named days [][]

for (i=0; i<=6 ; i++)

printf (“\n %s”,&days[i][0]);

 

Similarly if we want to read the strings into array from the keyboard we will use the following statement:

for (i=0; i<=6 ; i++)

scanf (“\n %s”,days[i]);

 

Following program will clear this concept more.

/* Program - st7.c */

#include

main()

{

char days[7][10] = {

"MONDAY",

"TUESDAY",

"WEDNESDAY",

"THRUSDAY",

"FRIDAY",

"SATURDAY",

"SUNDAY "

};

int choice;

printf("\nEnter any week day number : ");

scanf("%d", &choice);

if ((choice >=1)&&(choice<=7))

printf("\nYou have entered : %s",days[choice-1]);

else

printf("\nYou have entered wrong number.");

}

 

Here are some sample outputs of this program….

First Run :

Enter any week day number : 3

You have entered : WEDNESDAY

Second Run :

Enter any week day number : 8

You have entered wrong day number.

You can also receive array of characters through the console using the scanf() function.

 

 


Like it on Facebook, Tweet it or share this article on other bookmarking websites.

No comments