Strings in C

Strings:

A string represents a group of characters. In C, we can create strings in two ways. The first way is to declare a character-type 1D array and initialize it with characters.

char name[] = "nav";
char vehicle[] = "ka98765";

Here, the size of the 2D array. Now, the marks obtained by several such classes in a school become an example for 3D array.3D array can be created in 2 ways. The first way is to declare the array is not required. Since we are initializing the array with the characters, the compiler can understand the size depending upon the number of characters.

Another way to create a string is by declaring a character type array with some size and later store the characters into the array.

char name[20];

Here, name[20] is the character type array with size 20. Using scanf() function, we can store characters into this array, as:

scanf("%s",name);

To, input a string into a program, we can use gets() function in addition to scanf() as,

gets(name);

Here, format specifier “%s” is not required, since gets() function is specifically designed to accept string only.

program to accept a string using scanf()

#include<stdio.h>
void main()
{
   char name[15];
   printf("\n Enter name: ");
   scanf("%s", name);
   printf("\n You entered: %s", name);
}

Output:

Entered name: Nav Tutorials << Press Enter >>
You entered: Nav Tutorials

In above output, we are entering Navtutorials, but scanf() function has taken only ‘Nav’. When scanf() function sees a space in the string, it takes it as end of the string and hence it reads up to ‘Nav’ only. But this problem can be elimintaed by using “%[^\n]” specifier which reads the string up to the output.

Storage of strings in memory:

Any string is stored in the form of individual characters in memory. When we enter ‘Nav Tutorials’,it is stored in the memory with a ‘\0’ additionally added at the end. ‘\0’ is called NULL character. This character ‘\0’ which is added at the end of the string is useful to know where the string is ending memory. So, while reading the string, the processor accesses the string character by character till it sees the ‘\0’

Fig : Storage of a string in memory.

It is possible to access the string character by character till ‘\0’ is enountered as:

while(name[i]!='\0')
{
   putchar(name[i]);
   i++;
}

This loop reads the characters name[0], name[1],name[2],… as long as ‘\0’ is not encountered. Once ‘\0’ is read, it represents the end of string and hence the loop terminates.

Naveed Tawargeri
 

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.