How can you reverse a string in the C programming language?
There are multiple methods to achieve string reversal in the C language, and here is one common method:
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[] = "hello world";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
In the above code, we first define a function called reverseString, which takes a pointer to a string as a parameter and reverses the string. The function first calculates the length of the string, then uses a loop to swap the first half and second half of the string. Finally, in the main function, we define a string array and reverse the strings by calling the reverseString function, and output the result.