逆序

有一個字符數組的內容爲:”student a am i”,請你將數組的內容改爲”i am a student”.

要求:

不能使用庫函數。只能開闢有限個空間(空間個數和字符串的長度無關)。

tneduts a ma i -> i am a student
代碼如下

#include <stdio.h>
#include <assert.h>
#include <windows.h>

void str_switch(char *start, char *end)
{
    assert(start != NULL  && end != NULL);
    while (start < end)
    {
        *start = *start ^ *end;
        *end = *start ^ *end;
        *start = *start ^ *end;
        start++;
        end--;
    }
}

int main()
{
    char msg[] = "student a am i";
    char *p = msg;
    char *q = p;
    printf("%s\n", msg);

    while (*p != '\0')
    {
        if ( isspace(*p) )
        {
            str_switch(q, p - 1);
            q = p+1;
        }
        p++;
    }
    str_switch(q, p - 1);
    str_switch(msg, msg + strlen(msg) - 1);
    printf("%s\n", msg);
    system("pause");
    return 0;
}
發佈了36 篇原創文章 · 獲贊 44 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章