Latest web development tutorials

C Exercise Examples 35 - to reverse a string

100 cases of classic C language 100 cases of classic C language

Title: reverse a string, such as the string "www.w3big.com" inverted "moc.boonur.www".

Program Analysis: None.

Source Code:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

#include <stdio.h>


void reverse(char* s)
{
    // 获取字符串长度
    int len = 0;
    char* p = s;
    while (*p != 0)
    {
        len++;
        p++;
    }
    
    // 交换 ...
    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.w3big.com";
    printf("'%s' =>\n", s);
    reverse(s);           // 反转字符串
    printf("'%s'\n", s);
    return 0;
}

The above example output is:

'www.w3big.com' =>
'moc.boonur.www'

100 cases of classic C language 100 cases of classic C language