C – Introduction to Strings

String:

  • String is a one-dimensional character array.
  • String is a collection symbols (alphabets, digits and special symbols).
  • Strings must be represented with double quotes.
Syntax:Example:
char identity[size];char name[20];

Memory representation:

  • We can store only ‘n-1’ characters into an array of size ‘n’.
  • Last character of every string is ‘\0’
  • ASCII value of ‘\0’ character is 0.

String Format Specifier(%s):

  • We use %s to read and display strings.
  • To process character by character, we use %c specifier.

Program to display String:

#include<stdio.h>
int main()
{
            char str[20] = “Hello” ;
            printf(“%s all \n” , str); 
            return 0;
}

We can display complete character array in single statement using %s:

#include<stdio.h>
int main()
{
            char str[4] = {‘a’,’b’,’c’};
            printf(“String is : %s\n” , str);  
            return 0;
}

In C, duplicate strings get different memory locations:

== operator only compares the addresses of strings, hence following program outputs “Strings are not equal”

int main()
{
            char s1[10] = “abc”;
            char s2[10] = “abc”;
            if(s1==s2)
                        printf(“Strings are equal \n”);
            else
                        printf(“Strings are not equal \n”);        
            return 0;
}
Scroll to Top