How can you swap the order of strings in C language?
To reverse the order of a string, you can use a loop to output the characters in reverse. Below is an example code:
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
char temp;
for (int i = 0; i < length/2; i++) {
temp = str[i];
str[i] = str[length-1-i];
str[length-1-i] = temp;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
This code will reverse the order of the string “Hello, World!” and output “!dlroW ,olleH”. By swapping the position of each character through a loop, string reversal can be achieved.