Built with Tutify.io

    AIStudyLabs

    Practical Examples: Substring and Reverse String

    Practical Examples: Substring and Reverse String

    Introduction

    In this lesson, we will explore practical examples related to strings and arrays in C programming. You will learn how to implement substring extraction using array indexing techniques, reverse strings through efficient character swapping, use loops to manipulate string data, manage memory for dynamic string arrays, and understand the role of string terminators in array processes. By the end of this lesson, you'll be able to confidently apply these concepts in your C programming tasks.

    Implementing Substring Extraction

    Substring extraction is a common task when working with strings. Using array indexing, we can extract a substring from a given string by specifying the start index and the length of the substring.

    Code Example: Substring Extraction

    Here’s a simple function to extract a substring from a given string:

    #include <stdio.h>
    #include <string.h>
    
    void substring(char *src, char *dest, int start, int length) {
        for (int i = 0; i < length; i++) {
            dest[i] = src[start + i];
        }
        dest[length] = '\0'; // Null terminator for the new string
    }
    
    int main() {
        char source[] = "Hello, World!";
        char result[20]; // Ensure the destination has enough space
    
        substring(source, result, 0, 5);
        printf("Extracted substring: %s\n", result);
        return 0;
    }
    

    Program Explanation:

    1. The substring function takes the source string, destination string, starting index, and length as arguments.
    2. It uses a for loop to copy characters from the source to the destination array.
    3. A null terminator is added at the end of the destination string.
    4. The main function initializes a source string and calls the substring function.

    Expected Output:

    Extracted substring: Hello
    

    Reversing a String

    Reversing a string is another common string manipulation task. This can be efficiently done by swapping characters in the array from both ends.

    Code Example: Reverse String

    Below is a function to reverse a string:

    #include <stdio.h>
    #include <string.h>
    
    void reverseString(char *str) {
        int start = 0;
        int end = strlen(str) - 1;
        while (start < end) {
            // Swap the characters
            char temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
    
    int main() {
        char str[] = "Hello, World!";
        reverseString(str);
        printf("Reversed string: %s\n", str);
        return 0;
    }
    

    Program Explanation:

    1. The reverseString function uses two indices: start and end.
    2. A while loop continues until start is less than end.
    3. Characters at these indices are swapped until the whole string is reversed.
    4. The main function demonstrates this on a sample string.

    Expected Output:

    Reversed string: !dlroW ,olleH
    

    Utilizing Loops for String Manipulation

    Both substring extraction and string reversal utilize loops for character manipulation. Familiarity with loops allows for various operations on strings, like finding character counts or checking for palindromes.

    Memory Management for Dynamic String Arrays

    Dynamic arrays in C provide flexibility when dealing with string data. The malloc() function from the stdlib.h library can allocate necessary memory based on user input or program logic. Unlike static arrays, dynamic arrays can adjust in size, which is useful when the length of strings varies.

    Code Example: Dynamic String Array

    Here's a simple usage with malloc():

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int length;
        printf("Enter length of string: ");
        scanf("%d", &length);
    
        char *dynamicStr = (char *)malloc((length + 1) * sizeof(char)); // +1 for null terminator
        if (dynamicStr == NULL) {
            printf("Memory allocation failed!\n");
            return 1;
        }
    
        printf("Enter string: ");
        scanf("%s", dynamicStr);
        printf("You entered: %s\n", dynamicStr);
    
        free(dynamicStr); // Free allocated memory
        return 0;
    }
    

    Expected Output:

    Enter length of string: 5
    Enter string: Hello
    You entered: Hello
    

    Understanding String Terminators

    In C, strings are characterized by the null terminator \0, which signifies the end of the character array. This is crucial for string functions as they rely on this terminator to know where the string ends. Failure to null-terminate strings can lead to undefined behavior when processing them.

    Summary / Key Takeaways

    In this lesson, we covered practical examples of substring extraction and string reversal:

    C Programming Fundamentals: From Zero to Confident C Coder — Arrays and Strings

    Introduction to Programming and C

    Variables and Data Types

    Control Structures: Conditions and Loops

    Functions in C

    Arrays and Strings

    Working with Pointers

    File Handling in C

    Structures and Unions in C

    Project Development and Implementation

    Advanced C Concepts and Best Practices

    Tutorial Not Found