Reverse a C-String
In this quick article, we’ll explore how to reverse a C-String, which is a null-terminated ('\0') block of a contiguous sequence of characters.
The standard solution is to loop through the first half of the given C-string using a loop and swap the current character with the corresponding character on the other half of the C-string. We can do this in the following ways:
1. Using simple for-loop
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <stdio.h> #include <string.h> // Function to reverse a C-string without using pointers arithmetic void reverse(char* str) { // get the length of the string int n = strlen(str); // start swapping characters from both ends of the string for (int i = 0, j = n - 1; i < j; i++, j--) { char ch = str[i]; str[i] = str[j]; str[j] = ch; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
2. Using pointers arithmetic
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> #include <string.h> // Function to reverse a C-string using pointers arithmetic void reverse(char* str) { // if `str` is NULL, do nothing if (str == NULL) { return; } // get pointer to the end of the last character in the string char* end_ptr = str + (strlen(str) - 1); // start swapping characters from both ends of the string while (end_ptr > str) { char ch = *str; *str = *end_ptr; *end_ptr = ch; // increment str and decrement end_ptr ++str, --end_ptr; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
3. Using XOR operator
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <string.h> // Function to reverse a C-string using XOR operator void reverse(char* str) { // if `str` is NULL, do nothing if (str == NULL) { return; } // get pointer to the end of the last character in `str` char* end_ptr = str + (strlen(str) - 1); // start swapping characters from both ends of the string. // `str` should be strictly less than `end_ptr` since XOR fails // when both refer to the same memory location while (str <= end_ptr) { // swap the values pointed by both pointers *str = *str ^ *end_ptr; *end_ptr = *str ^ *end_ptr; *str = *str ^ *end_ptr; // increment str and decrement end_ptr ++str, --end_ptr; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
That’s all about reversing a C-String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)