Reverse a String Without Using strrev, strlen, or sizeof in C

Reversing a string is a fundamental problem in C programming. While standard library functions like strrev() or strlen() make this easy, it's important to understand how to reverse a string manually using basic operations.

This approach is useful for learning string traversal, pointer manipulation, and loop constructs in C.

Logic to Reverse a String Without strrev or strlen

1. Initialize two indices: start = 0 and end = 0.

2. Traverse the string using a loop to find the end of the string (till null character '\0').

3. Decrement end by 1 to point to the last character of the string.

4. Swap characters at start and end indices and move start forward and end backward until start >= end.

5. This will reverse the string in place without using any built-in functions.

C Program to Reverse a String Without Using strrev or strlen

C
Reverse string manually
#include <stdio.h>

int main() {
    char str[100];
    int start, end;
    char temp;

    printf("Enter a string: ");
    scanf("%[^
]", str); // Read string including spaces

    // Find length manually
    end = 0;
    while(str[end] != '\0') {
        end++;
    }
    end--; // Point to last character

    start = 0;
    // Reverse string using swapping
    while(start < end) {
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }

    printf("Reversed String: %s\n", str);

    return 0;
}
Sample Input:
Enter a string: Hello World
Output:
Reversed String: dlroW olleH

Explanation

• The program first reads the string including spaces using '%[^ ]' format specifier.

• The 'end' index is calculated manually by traversing the string until '\0' is encountered.

• We then use a loop to swap characters at 'start' and 'end' until they meet or cross.

• This results in an in-place reversal of the string without using any library functions.

Advantages of This Approach

• Does not rely on library functions, making it portable.

• Demonstrates understanding of basic loops, indexing, and string handling.

• Efficient as it reverses the string in place without extra memory.

Conclusion

Reversing a string manually is a foundational C programming exercise that strengthens understanding of arrays, loops, and memory access. By avoiding built-in functions like strrev() and strlen(), programmers learn to manipulate strings efficiently and gain a deeper grasp of character arrays in C.