Latest web development tutorials

C 練習實例35 – 字符串反轉

C 語言經典100例 C語言經典100例

題目:字符串反轉,如將字符串"www.w3big.com"反轉為"moc.boonur.www"。

程序分析:無。

程序源代碼:

//  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;
}

以上實例輸出結果為:

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

C 語言經典100例 C語言經典100例