Strings in C

05 min read

A string is a sequence of characters. It is represented as an array of characters and the end of the string is marked by the NULL ('\0') character. String constants are generally enclosed in double quotes. String functions are defined in the header file string.h

String declaration:  char a[ 10];

String initialization:  Every string ends with a null character '\0'. So, along with this character, the number of elements is 4. So, declare the array with 4 elements.

char a[4]= {'V', 'I', 'T'}; 

char a[]= {'V', 'I', 'T'} ;     

char a[]="VIT"; 

char a[4]="VIT"; 

char a[3]={'V', 'I', 'T'} ; // This is wrong syntax

 

Functions used in strings:

1) gets(): A function that can be used to read a string

Syntax: gets(character array);

2) puts(): A function used to print a string

Syntax: puts(character array);

 

Example:

#include<stdio.h>
int main()
{  
    char str[50];
    scanf("%s",str);
    printf("%s",str);
    return 0;
}
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error