Strings in C Language


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];

Here,

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.

FunctionPurposes
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,

Example

 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
", s1, s2 );    strcat( s1, s2);    printf("String concatenation: %s
", s1 );    len = strlen(s1);    printf("Length of string s1 : %d
", len );    com = strcmp(s1,s2);    printf("Comparison of strings s1 and s2 : %d
", com );    return 0; }

Output

Strings s1 and s2 : WorldWorld
String concatenation: WorldWorld
Length of string s1 : 10
Comparison of strings s1 and s2 : 87

Updated on: 24-Jun-2020

985 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements