Strings in C

A string in C is a sequence of characters terminated by a null character '0'. Strings are used to represent text in C programming, and they are implemented as arrays of characters. Strings are widely used for tasks like input/output, text processing, and data manipulation.

Definition

A string in C is an array of characters that is terminated by the special character '0' to indicate the end of the string. Strings can be manipulated using string handling functions like strlen(), strcpy(), strcat(), etc.

String Declaration and Initialization

In C, strings can be declared in two ways:

Syntax:

                
char str1[20];  // Declaration of character array
char str2[] = "Hello, World!";  // Initialization with a string literal
                
            

Example: Declaring and Printing a String

This example demonstrates how to declare a string and print it using the printf() function.

Example Code:

                
#include <stdio.h>
int main()
{
    char str[] = "Hello, C World!";
    printf("String: %s\n", str);  // Using %s to print the string
    return 0;
}
                
            

Output

String: Hello, C World!

String Length

In C, the length of a string can be calculated using the strlen() function, which counts the number of characters in the string excluding the null character '0'.

Example: Calculating String Length

                
#include <stdio.h>
#include <string.h>
int main() 
{
    char str[] = "Hello, C!";
    int length = strlen(str);  // strlen() function calculates string length
    printf("Length of string: %d\n", length);
    return 0;
}
                
            

Output

Length of string: 9

String Manipulation Functions

C provides several functions to manipulate strings. Below are some common string functions:

Example: Using strcpy and strcat

This example demonstrates the use of strcpy() and strcat() functions to copy and concatenate strings.

Example Code:

                
#include <stdio.h>
#include <string.h>
int main() 
{
    char str1[20] = "Hello, ";
    char str2[] = "World!";
        
    // Copying str2 to str1
    strcpy(str1, str2);
    printf("After strcpy: %s\n", str1);
        
    // Concatenating str1 with str2
    strcat(str1, " C!");
    printf("After strcat: %s\n", str1);
    
    return 0;
}
                
            

Output

After strcpy: World!
After strcat: World! C!

Key Points