C语言 把student a am i 变成 i am a student(两种方法)

student a am i 变成 i am a student

方法1:指针

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

void fanw(char *l, char *r)
{
    char* left = l;
    char* right = r;
    char temp;
    while (left < right)
    {
        temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }
}
//解析出来每个单词  
void fans(char *p)
{

    while (*p != '\0')
    {
        char *pst = p;
        while (*p != '\0' && *p != ' ')
        {
            p++;
        }
        fanw(pst, p - 1);
        p++;
    }
}

int main()
{
    char p[30] = "student a am i";
    int len = strlen(p);
    printf("原字符串是:%s\n", p);
    printf("翻转后的字符串是:");
    fanw(p, p + len - 1);
    fans(p);
    printf("%s\n", p);
    return 0;
}

方法2:数组


void reservestring(char a[], int x, int y)
{
    x = x - 1;
    while (x >= y)
    {
        char tmp = a[x];
        a[x] = a[y];
        a[y] = tmp;
        x--;
        y++;
    }
}

void reserve(char a[], int num)
{
    int x = 0;
    int y = 0;
    num += 1;
    while (num--)
    {
        if (a[x] == ' ' || a[x] == '\0')
        {
            reservestring(a, x, y);
            y = x + 1;
            x = y;
        }
        else
        {
            x++;
        }
    }
    reservestring(a, strlen(a), 0);
}
int main()
{
    char a[] = "student a am i";
    reserve(a, strlen(a));
    printf("%s", a);
    system("pause");
}

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/80158560
今日推荐