String reverse in Data Structure using C

In C, we can reverse a string using a loop and swapping the characters at opposite ends of the string. Here's an example:

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

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);

    int length = strlen(str);
    int i;
    for (i = 0; i < length/2; i++) {
        char temp = str[i];
        str[i] = str[length-i-1];
        str[length-i-1] = temp;
    }

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

    return 0;
}
```

In this program, we first declare a character array `str` to store the input string. We then prompt the user to enter a string using the `scanf()` function. Next, we find the length of the string using the `strlen()` function and store it in the variable `length`. We then use a loop to swap the characters at opposite ends of the string. Finally, we print the reversed string using `printf()`.


Note that we only need to swap the first half of the string with the second half, as the characters in the middle remain unchanged when the string is reversed. Also, make sure that the string has enough space to accommodate the reversed string, including the null character (`\0`) at the end.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext