输入一个字符串编写程序将其倒置 C语言 例如 abcd换成dcba 我是个好同志换成志同好个是我

如题所述

#include <stdio.h>
#include <stdlib.h>

void reverseStr(char* x)
{
    int slen;
    char* buf;
    char* p;
    char* p2;
    
    p = x;
    while(*p) ++p;
    slen = p - x;
    
    buf = (char*) malloc(slen + 1);
    p = x; p2 = buf;
    while(*p) *(p2++) = *(p++);
    *p2 = 0;
    
    p = buf;
    p2 = x + slen;
    *p2 = 0;
    --p2;
    
    while(*p) {
        if (*p < 0) {
            *(p2 - 1) = *p;
            *p2 = *(p + 1);
            ++p;
            --p2;
        } else {
            *p2 = *p;
        }
        ++p;
        --p2;
    }
    
    free(buf);
}

int main()
{
    char x[] = "abcd我是个好同志";
    reverseStr(x);
    puts(x);
    return 0;
}

还要能搞中文啊,你的要求略麻烦……

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-06
#include <stdio.h>
#include <string.h>

char *swap(char *s)
{
        int i;
        int l = strlen(s) - 1;

        for (i = 0; i <= l / 2; i++) {
                char t = s[i];
                s[i] = s[l - i];
                s[l - i] = t;
        }

        return s;
}

int main(void)
{
        char buf[128];

        gets(buf);
        puts(swap(buf));
        return 0;
}

只支持英文

第2个回答  2013-06-06
很简单啊,就是头和尾换,第二和倒数第二换如此类推直到中间。
第3个回答  2013-06-06
原型:extern char *strrev(char *s);

用法:#include <string.h>

功能:把字符串s的所有字符的顺序颠倒过来(不包括空字符NULL)。

说明:返回指向颠倒顺序后的字符串指针。
相似回答