Learn Strings in C

What is a string?

A string literal nor a string constant is a sequence of zero or more characters enclosed by " ". A string is an array of characters terminated by a special character called the 'null character' (\0).

Each character in a string is stored in 1 byte in its ASCII code.

As string is stored in the form of array we can access individual characters from it.

Declaration And Initialization of String Variable


char string_name[size]

Here the string_name is the name of string and size determines the number of characters it can hold.

We can initialize a string either as
  1. 
    char name[]={'S','m','e','e','r','a','\0'};
    
    
    In this type, we have to include the null character (\0) explicitly in the string.
  2. OR
  3. 
    char name[]="Sameera";
    
    
    In this type, the compiler automatically includes the null character.

How to accept a string?

Most commonly we can accept a string either as

Using scanf() function


printf("\n Enter your name:- ");
scanf("%s",name);

We don't use amerpsand (&) here. We will see why later. By using scanf() function we can accept only the string before first occurrence of space i.e. we can accept only a word.

Using gets() function


printf("\n Enter your name:- ");
gets(name);

By using gets() function to accept string we can accept a whole sentence until we press Enter (carriage return). So with this type we can accept a whole sentence.

But there is a threat of using this. There is some memory available to store things temporarily called as buffer. If we continue to write the sentence and don't press enter it is possible that we can give the buffer more than it can hold it is called as 'buffer overflow'. To avoid this we can take the input character by character using for loop.

How to output the string to the console

To output the string we can use either use printf() function or puts() function.

Using printf() function to output the string


printf("\n Thank you %s for learning C on computerscienceai.blogspot.com ",name);

/*

If your string name contains "Abhijit Kokane"

It will output


Thank you Abhijit Kokane for learning C on computerscienceai.blogspot.com


*/

printf() function does not automatically out your message to the newline. For that you have to include new line character (\n) explicitly.

Using puts() function to output the string


puts(name);

/*

If name contains "Abhijit Kokane"

It will output the same on new line

Output- 

Abhijit Kokane

*/


Here puts() function adds the newline character (\n) implicitly.