String In C

String

C Strings

String in C language is an array of characters that is terminated by \0 (null character).

There are two ways to declare string in c language.

  • By char array
  • By string literal

Let's see the example of declaring string by char array in C language.

char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As you know well, array index starts from 0, so it will be represented as in the figure given below.

While declaring string, size is not mandatory. So you can write the above code as given below:

char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

You can also define string by string literal in C language. For example:

char ch[]="javatpoint"; 

In such case, '\0' will be appended at the end of string by the compiler.

Difference between char array and string literal

The only difference is that string literal cannot be changed whereas string declared by char array can be changed.

String Example in C

Let's see a simple example to declare and print string. The '%s' is used to print string in c language.

#include <stdio.h>  
void main ()  
{  
   char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};  
   char ch2[11]="javatpoint";  
  
   printf("Char Array Value is: %s\n", ch);  
   printf("String Literal Value is: %s\n", ch2);  
}

Output :

Char Array Value is : javatpoint
String Literal Value is : javatpoint