String in C Programming

String in C programming language is a one-dimensional array of characters which is terminated by a null character(‘\0’). A character array which is not null terminated is not a valid C string. In a C string, each character occupies one byte of memory including null character.

Null character marks the end of the string, it is the only way for the compiler to know where this string is ending. Strings are useful when we are dealing with text like Name of a person, address, error messages etc.

Examples of C Strings

  • “A”
  • “TechCrashCourse”
  • “Tech Crash Course”
  • ” “
  • “_18u,768JHJHd87”
  • “PROGRAM”

Below is the representation of string in memory.

C-Strings

Points to Remember about Strings in C

  • C Strings are single dimensional array of characters ending with a null character(‘\0’).
  • Null character marks the end of the string.
  • Strings constants are enclosed by double quotes and character are enclosed by single quotes
For Example

String constant : “TechCrashCourse”
Character constant: ‘T’

  • If the size of a C string is N, it means this string contains N-1 characters from index 0 to N-2 and last character at index N-1 is a null character.
  • Each character of string is stored in consecutive memory location and occupy 1 byte of memory.
  • The ASCII value of null character(‘\0’) is 0.

Declaration of Strings in C

String is not a basic data type in C programming language. It is just a null terminated array of characters. Hence, the declaration of strings in C is similar to the declaration of arrays.

Like any other variables in C, strings must be declared before their first use in C program.
Syntax of String Declaration
char string_name[SIZE_OF_STRING];
In the above declaration, string_name is a valid C identifier which can be used later as a reference to this string. Remember, name of an array also specifies the base address of an array.

SIZE_OF_STRING is an integer value specifying the maximum number of characters which can be stored in this string including terminating null character. We must specify size of string while declaration if we are not initializing it.
Examples of String Declaration

  • char address[100];
  • char welcomeMessage[200];

C Does not provide support for boundary checking i.e if we store more characters than the specified size in string declaration then C compiler will not give you any error.

Initialization of Strings

In C programming language, a string can be initialized at the time of declarations like any other variable in C. If we don’t initialize an array then by default it will contain garbage value.
There are various ways to initialize a String Initialization of string using a character array

char name[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
or 
char name[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};

In the above declaration individual characters are written inside single quotes(”) separated by comma to form a list of characters which is wrapped in a pair or curly braces. This list must include a null character as last character of the list.

If we don’t specify the size of String then length is calculated automatically by the compiler.
Initialization of string using string literal

char name[16] = "TechCrashCourse";
or
char name[] = "TechCrashCourse";

In above declaration a string with identifier “name” is declared and initialized to “TechCrashCourse”. In this type of initialization , we don’t need to put terminating null character at the end of string constant. C compiler will automatically inserts a null character(‘\0’), after the last character of the string literal.

If we don’t specify the size of String then length is calculated automatically by the compiler. The length of the string will be one more than the number of characters in string literal/constant.
Initialization of string using character pointer

char *name = "TechCrashCourse";

In the above declaration, we are declaring a character pointer variable and initializing it with the base address of a string constant. A null terminating character is automatically appended by the compiler. The length of the string will be one more than the number of characters in string constant.

C Program showing String Initialization

String in C Programming

#include <stdio.h>
#include <conio.h>
  
void main(){  
   char nameOne[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
   char nameTwo[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
   char nameThree[16] = "TechCrashCourse";
   char nameFour[] = "TechCrashCourse";
   char *nameFive = "TechCrashCourse";
   
   printf("%s\n", nameOne); 
   printf("%s\n", nameTwo); 
   printf("%s\n", nameThree); 
   printf("%s\n", nameFour);
   printf("%s\n", nameFive); 
    
   getch();
   return 0; 
}

Output

TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse

String Input Output in C

Standard library functions for reading strings

  • gets() : Reads a line from stdin and stores it into given character array.
  • scanf() : Reads formatted data from stdin.
  • getchar() : Returns a character from stdin stream.
  • fscanf() : Read formatted data from given stream.

Standard library functions for printing strings

  • puts() : Writes a string to stdout stream excluding null terminating character.
  • printf() : Print formatted data to stdout.
  • putchar() : Writes a character to stdout stream.
  • fprintf() : Writes formatted output to a stream.

C Program to read and print strings

C Program to read and print strings

#include <stdio.h>
#include <conio.h>
 
int main(){
    char name[30], city[100], country[100];
    char c;
    int i=0;
     
    printf("Enter name: ");
    /* Reading string using gets function */
    gets(name);
     
    printf("Enter city: ");
    /* Reading string using getchar function */
    while((c = getchar()) != '\n'){
        city[i]=c;
        i++;
    }
    city[i]='\0';
     
    printf("Enter country: ");
    /* Reading string using scanf function */
    scanf("%s", country);
     
    /* Printing string using printf() */
    printf("%s\n", name);
    /* Printing string using puts() */
    puts(city);
    /* Printing string using putchar() */
    for(i=0; country[i] != '\0'; i++)
       putchar(country[i]);
     
    getch();
    return 0;
}

Output

Enter name: Jack
Enter city: New York
Enter country: USA
Jack
New York
USA

String Handling Standard Library Function
string.h header file contains a wide range of functions to manipulate null-terminated C strings.

Below are some commonly used string handling functions of string.h header file.

Function Description
strcat() It appends one string at the end of another string.
strchr() It searches for the first occurrence of a character in the string.
strcmp() It compares two strings character by character.
strcpy() It copies characters from one string into another string.
strlen() It returns the length of a string.
strstr() It searches for the first occurrence of a string in another string.
strtok() It breaks a string into smaller tokens.

C Program to show the use of string handling functions of string.h header file

C Program to show the use of string handling functions of string.h header file

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main(){
   char inputString[50];
   char copyString[60];
    
   printf("Enter a string: ");
   gets(inputString);
 
   /* Printing length of string using strlen() */
   printf("Length of %s : %d\n", inputString, strlen(inputString));
 
   /* copying inputString into copyString */
   strcpy(copyString, inputString);
   printf("Copied String : %s\n", copyString);
 
   /* comparing inputString and copyString string*/
   if(strcmp(copyString, inputString)){
       printf("Both Strings are Not Equal\n");
   } else {
       printf("Both Strings are Equal\n");
   }
 
   getch();
   return 0;
}

Program Output

Enter a string: TechCrashCourse
Length of TechCrashCourse : 15
Copied String : TechCrashCourse
Both Strings are Equal