What is a string? Declare and initialize the strings in C language


An array of characters (or) collection of characters is called a string.

Declaration

Refer to the declaration given below −

char stringname [size];

For example - char a[50]; a string of length 50 characters.

Initialization

The initialization is as follows −

  • Using single character constant −

char string[20] = { ‘H’, ‘i’, ‘l’, ‘l’, ‘s’ ,‘\0’}

  • Using string constants −

char string[20] = "Hello":;

  • ‘\0’ is called a null character. It marks the end of the string.

  • ‘\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\0’ at the end if a single character is given.

Accessing − There is a control string "%s" used for accessing the string, till it encounters ‘\0’.

Example

Following is the C program for a string −

#include<stdio.h>
main ( ){
   char a[10] = "Hello";
   clrscr ( );
   printf ( " given string is %s",a)
   getch ( );
}

Output

When the above program is executed, it produces the following result −

Given string is Hello

Updated on: 08-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements