C program to find reverse of a string

Category: C Program
Tags: #cprogram#string

Learn how to reverse a string in C with detailed examples. This guide covers both manual string reversal and using the strrev function, complete with sample code and explanations.

Reversing a string is a common task in programming, often used in text processing and data manipulation. In this article, we'll walk through two methods to find the reverse of a given string in C: using basic string manipulation techniques and using the strrev function.

Introduction

Reversing a string involves creating a new string that has the characters of the original string in reverse order. We'll explore both manual and library-based approaches to accomplish this task.

Method 1: Manual String Reversal

Algorithm

  1. Initialize Variables:
    • An array to hold the original string.
    • Another array to hold the reversed string.
    • Variables to track the length of the string and loop indices.
  2. Input the String:
    • Use standard input functions to read the string from the user.
  3. Reverse the String:
    • Calculate the length of the original string.
    • Use a loop to copy characters from the original string to the reversed string in reverse order.
  4. Print the Reversed String:
    • Output the reversed string to the console.

Write a C program to find reverse of a string

Here is the C program to find the reverse of a string manually:

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

int main() {
    char str[1000], rev[1000];
    int len, i, j;

    // Input string from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove the newline character at the end if present
    str[strcspn(str, "\n")] = '\0';

    // Calculate the length of the string
    len = strlen(str);

    // Reverse the string
    for (i = 0, j = len - 1; j >= 0; i++, j--) {
        rev[i] = str[j];
    }
    rev[len] = '\0'; // Null-terminate the reversed string

    // Print the reversed string
    printf("Reversed string: %s", rev);

    return 0;
}

We can also run a for loop using just single variable, just replace line 19-21 above to get same result

for (i = 0; j >= 0; i++) {
    rev[i] = str[len-i-1];
}

Output

Enter a string: ProCoding
Reversed string: gnidoCorP

Explanation

  1. Include Headers:
    • We include the standard input-output header (stdio.h) for input and output functions.
    • The string.h header is included for string manipulation functions like strlen and strcspn.
  2. Main Function:
    • We declare two character arrays: str to hold the original string and rev to hold the reversed string.
    • We also declare integer variables len to store the length of the string, and loop indices i and j.
  3. Input the String:
    • Using fgets, we read the input string from the user.
    • We use strcspn to remove the newline character that fgets may include at the end of the string.
  4. Calculate Length:
    • We use strlen to calculate the length of the input string.
  5. Reverse the String:
    • We use a for loop to copy characters from the original string to the reversed string in reverse order. The loop runs from the end of the original string to the beginning.
    • We ensure the reversed string is null-terminated by adding '\0' at the end.
  6. Print the Reversed String:
    • We use printf to output the reversed string to the console.

Reverse the string in place

In the previous program, we have used a separate array to store the reverse of array but if required we can modify the reverse of string in place.

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

int main() {
    char str[1000], temp;
    int len, i, j;

    // Input string from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove the newline character at the end if present
    str[strcspn(str, "\n")] = '\0';

    // Calculate the length of the string
    len = strlen(str);

    // Reverse the string
    for (i = 0, j = len - 1; i <= j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    // Print the reversed string
    printf("Reversed string: %s", str);

    return 0;
}

We can also use while loop ti get same result just replace the line 19-23 from -

i = 0;
j = len-1;
while (i <= j) {
   temp = str[i];
   str[i] = str[j];
   str[j] = temp;
   i++;
   j--;
}

Method 2: Using strrev Function

The strrev function from string.h provides a convenient way to reverse a string. Note that strrev is not part of the C standard library, but it is available in some environments.

Write a C program to find reverse of a string using strrev Function

Here is the C program to find the reverse of a string using the strrev function:

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

int main() {
    char str[1000];

    // Input string from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove the newline character at the end if present
    str[strcspn(str, "\n")] = '\0';

    // Reverse the string using strrev
    strrev(str);

    // Print the reversed string
    printf("Reversed string: %s", str);

    return 0;
}

Explanation

  1. Include Headers:
    • We include the standard input-output header (stdio.h) for input and output functions.
    • The string.h header is included for string manipulation functions like strlen and strcspn.
  2. Main Function:
    • We declare a character array str to hold the original string.
    • Using fgets, we read the input string from the user.
    • We use strcspn to remove the newline character that fgets may include at the end of the string.
    • We call strrev to reverse the string in place.
    • We use printf to output the reversed string to the console.

Edge Cases

  • Empty String:
    • If the input string is empty, the reversed string will also be empty.
  • Single Character:
    • If the input string contains only one character, the reversed string will be the same as the input string.
  • Special Characters:
    • Both programs correctly handle special characters and white space within the string.

Reverse string using pointers

If you want to learn how to reverse a string using pointers then check this:

C program to reverse a string using pointers


Recommended Posts