Nano Technology

Strings in C Programming


1. What is a String in C?

In C programming, a string is a sequence of characters stored in a character array and terminated by a special character called the null character ('\0').

Unlike some high-level languages, C does not have a built-in string data type. Instead, strings are represented using arrays of characters.

Strings in C Programming

2. String Declaration

A string is declared using a character array. The size of the array should be large enough to store all characters including the null character.


char name[20];

Here, name can store a string of up to 19 characters, with the last position reserved for '\0'.

3. String Initialization

Strings can be initialized at the time of declaration in different ways.


char city[] = "Hyderabad";
char course[10] = {'C','P','r','o','g','r','a','m','\0'};

When a string literal is used, the compiler automatically appends the null character at the end.

4. Input and Output of Strings

Strings can be read and displayed using standard input and output functions.


#include <stdio.h>

char name[20];
scanf("%s", name);
printf("%s", name);

The scanf() function reads a string until a whitespace is encountered. For reading full lines including spaces, functions like fgets() are preferred.

5. Common String Functions

C provides several built-in string handling functions through the <string.h> header file.

Function Purpose
strlen() Returns the length of a string
strcpy() Copies one string into another
strcat() Concatenates two strings
strcmp() Compares two strings

6. String Examples


#include <stdio.h>
#include <string.h>

int main()
{
    char s1[20] = "IPLTS";
    char s2[20] = "C Programming";

    printf("Length of s1 = %lu\n", strlen(s1));
    strcat(s1, s2);
    printf("Combined String = %s\n", s1);

    return 0;
}

This program demonstrates basic string operations such as length calculation and concatenation.

7. Difference Between Char Array & String

Char Array String
Stores individual characters Stores characters ending with '\0'
May or may not represent text Always represents text
No automatic termination Automatically terminated by null character
Can exist without meaning Must follow string format

8. Summary

  • Strings in C are stored as character arrays.
  • The null character marks the end of a string.
  • String handling functions are defined in <string.h>.
  • Understanding strings is essential for text processing.
Note: Mastery of strings is necessary before learning pointers, file handling, and advanced data structures.