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 String memory representation

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

#include <stdio.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); 
   
   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

#include <stdio.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]);
    
    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.


C Program to show the use of string handling functions of string.h header file
#include <stdio.h>
#include <string.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");
   }

   return 0;
}
Output
Enter a string: TechCrashCourse
Length of TechCrashCourse : 15
Copied String : TechCrashCourse
Both Strings are Equal

Best Practices for String Handling in C

  • Null-Termination : To avoid undefined behavior when utilizing string functions, always verify that strings are null-terminated ('0').
    char myString[] = "Hello";
    

  • Buffer Size Consideration : When working with user input or altering text dynamically, keep buffer sizes in mind to avoid buffer overflows.
    char userInput[50];
    // Limit input to 49 characters to leave 
    // space for null-termination
    scanf("%49s", userInput); 
    

  • Avoid Changing String Constants : Changing string constants results in undefined behavior. For mutable strings, always utilize character arrays or dynamic memory.
    // Avoid
    char *constantString = "This is constant.";
    // Prefer
    char mutableString[] = "This is mutable.";
    

  • Check Return Values :The majority of string functions include useful information, such as the number of characters processed. For error handling, look at these return values.
    char source[] = "Copy me!";
    char destination[10];
    if (strcpy(destination, source) != NULL) {
        // Successful copy
    } else {
        // Handle error
    }
    

  • Be Mindful of Performance : Some string functions may perform better in particular circumstances. Consider strncmp instead of strcmp for efficiency if you simply need to compare the first few characters of two strings.


Conclusion

To make programs that work well and are reliable, you need to know how strings work in C and how to use the right tools to change them. You can make C programs that handle and change text data quickly and easily by following best practices, being careful with strings, and making good use of the standard library functions. If you want to write code that works well and can be maintained, you need to know how to work with strings in C. This is true whether you are writing code for user input, file processing, or more complex programs.