Strings in C Language

CProgrammingServer Side Programming

String is an array of characters and terminated by a null character (\0). The null character is not placed by the user, the compiler places it at the end of string automatically.

The difference between an array and a string is that the compiler does not place null character at the end of array while in string, compiler places null character.

Here is the syntax of string in C language,

char myStr[size];


myStr: The string

size: Set the size of string

Initialize string in C language like show below −

char myStr[size] = “string”;
char myStr[size] = { ‘s’,’t’,’r’,’i’,’n’,’g’,’\0’ };

The following table displays functions of string in C language.

strcpy(s1, s2)Copies string s2 into string s2
strcat(s1, s2)Concatenates s2 onto end of s1
strlen(s1)Returns the length of string s1
strcmp(s1, s2)Returns 0 when s1 and s2 are same Greater than 0 when ASCII value of s1 is greater than s2 Lesser than 0 when ASCII value of s1 is lesser than s2
strchr(s1, ch)Returns the pointer to the first occurence of character ch in string s1
strstr(s1, s2)Returns the pointer to the first occurence of string s2 in string s1

Here is an example of string in C language,


 Live Demo

#include <stdio.h>
#include <string.h>
int main () {
   char s1[10] = "Hello";
   char s2[10] = "World";
   int len, com ;
   strcpy(s1, s2);
   printf("Strings s1 and s2 : %s\t%s\n", s1, s2 );
   strcat( s1, s2);
   printf("String concatenation: %s\n", s1 );
   len = strlen(s1);
   printf("Length of string s1 : %d\n", len );
   com = strcmp(s1,s2);
   printf("Comparison of strings s1 and s2 : %d\n", com );
   return 0;


Strings s1 and s2 : WorldWorld
String concatenation: WorldWorld
Length of string s1 : 10
Comparison of strings s1 and s2 : 87
Published on 08-Oct-2018 08:58:45