Reverse String in C: Step-by-Step Guide

You can use arrays and pointers in the C language to reverse the content of a string. You can follow these steps to achieve this.

  1. Create a function to reverse the contents of a string, the function prototype can be like this:
void reverseString(char* str);
  1. In the function, a pointer is used to point to the beginning of the string, while another pointer is used to point to the end of the string. By swapping the characters pointed to by these two pointers, the content of the string is reversed. The specific code is as follows:
void reverseString(char* str) {
    char* start = str;
    char* end = str + strlen(str) - 1;
    
    while(start < end) {
        char temp = *start;
        *start = *end;
        *end = temp;
        
        start++;
        end--;
    }
}
  1. Call this function in the main function, passing in the string that needs to be reversed as a parameter. For example:
int main() {
    char str[] = "Hello, world!";
    
    printf("Original string: %s\n", str);
    
    reverseString(str);
    
    printf("Reversed string: %s\n", str);
    
    return 0;
}

By running the code above, the original string “Hello, world!” will be reversed to “!dlrow ,olleH”.

bannerAds