Easy Tutorial
❮ C Structures C Exercise Example97 ❯

C Exercise Example 35

C Language Classic 100 Examples

Title: String reversal, such as reversing the string "www.tutorialpro.org" to "moc.boonur.www".

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include <stdio.h>

void reverse(char* s)
{
    // Get the length of the string
    int len = 0;
    char* p = s;
    while (*p != 0)
    {
        len++;
        p++;
    }

    // Swap...
    int i = 0;
    char c;
    while (i <= len / 2 - 1)
    {
        c = *(s + i);
        *(s + i) = *(s + len - 1 - i);
        *(s + len - 1 - i) = c;
        i++;
    }
}

int main()
{
    char s[] = "www.tutorialpro.org";
    printf("'%s' =>\n", s);
    reverse(s);           // Reverse the string
    printf("'%s'\n", s);
    return 0;
}

The output of the above example is:

'www.tutorialpro.org' =>
'moc.boonur.www'

C Language Classic 100 Examples

❮ C Structures C Exercise Example97 ❯