Strings in C Programming - Tutorial

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Strings

String Handling: Strings in C are arrays of characters ending with a null terminator (\0). They are handled using functions from the <string.h> library. Below, I'll explain some key functions for string handling and manipulation, with examples.

Key Functions from <string.h> Library:

Example Code:

#include <stdio.h>
#include <string.h> // Include the string library for string functions

int main() {
    // Declaration and initialization of strings
    char source[] = "Hello, World!";
    char destination[50]; // Allocate enough space for the destination string
    char anotherString[] = "Hello, World!";
    char modifiedString[50];

    // Using strlen to get the length of a string
    size_t length = strlen(source);
    printf("Length of source string: %zu\\n", length); // Output: 13

    // Using strcpy to copy a string
    strcpy(destination, source);
    printf("Destination string after strcpy: %s\\n", destination); // Output: Hello, World!

    // Using strcmp to compare two strings
    int cmpResult = strcmp(source, anotherString);
    if (cmpResult == 0) {
        printf("The strings are equal.\\n"); // Output: The strings are equal.
    } else if (cmpResult < 0) {
        printf("Source is less than anotherString.\\n");
    } else {
        printf("Source is greater than anotherString.\\n");
    }

    // Modifying and processing strings
    strcpy(modifiedString, source); // Copy source into modifiedString
    modifiedString[7] = 'C'; // Modify a character in modifiedString
    printf("Modified string: %s\\n", modifiedString); // Output: Hello, Corld!

    return 0;
}

Detailed Explanation:

String Declaration and Initialization:

char source[] = "Hello, World!";
char destination[50];
char anotherString[] = "Hello, World!";
char modifiedString[50];

Using strlen:

size_t length = strlen(source); printf("Length of source string: %zu\\n", length);

Using strcpy:

strcpy(destination, source); printf("Destination string after strcpy: %s\\n", destination);

Using strcmp:

int cmpResult = strcmp(source, anotherString); if (cmpResult == 0) { printf("The strings are equal.\\n"); } else if (cmpResult < 0) { printf("Source is less than anotherString.\\n"); } else { printf("Source is greater than anotherString.\\n"); }

String Modification:

strcpy(modifiedString, source); modifiedString[7] = 'C'; printf("Modified string: %s\\n", modifiedString);
Previous Next
Modern Footer