Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.
Question
Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.
Solution
Sure, here is a simple way to reverse a string in C:
- First, you need to find the length of the string. You can use the
strlen()function from the string.h library for this.
#include <string.h>
int length = strlen(string);
- Next, you need to create a loop that will go through the string from the end to the beginning. You can use a for loop for this.
for(int i = length - 1; i >= 0; i--)
- Inside the loop, you simply print out the character at the current position.
printf("%c", string[i]);
- Put it all together, and you get:
#include <stdio.h>
#include <string.h>
int main() {
char string[] = "Hello, World!";
int length = strlen(string);
for(int i = length - 1; i >= 0; i--) {
printf("%c", string[i]);
}
return 0;
}
This program will print out "!dlroW ,olleH", which is the reverse of "Hello, World!".
Similar Questions
Write a C function, which reverses a given string and returns a pointer to reversed string.char *reverse(char *str);
Program to Reverse a String using Pointers
Write a program in C to print a string in reverse using a character pointer.Also print the uppercase of the first letter of the reversed word.
algorithm for a program to reverse a number in c programming
Write c function to reverse words in sentence (without using external arrays)
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.