“I am a student”反转成“student a am I”

方法是先反转整个字符串,然后再反转字串。譬如先将“I am a student”反转为“tneduts a ma I”,然后再对每个字串(空格分割)反转一次。思想就那么简单吧。


第一种:

#include <stdio.h>

void main()
{
    char str[]="you are a student";
    printf(str);
    printf("\n");

    char *p,*q;
    char temp;
    p=q=str;
    while(*q!='\0')
    {
        q++;
    }
    q--;
    while(p<=q)
    {
        temp=*p;
        *p=*q;
        *q=temp;
        p++;
        q--;
    }//反转整个字符串

    printf(str);
    printf("\n");

    char *s;
    q=p=s=str;//指针指向开始位置
    while(*q!='\0')
    {
        if(*q==' '||*(q+1)=='\0')
        {
            p--;
            if(*(q+1)=='\0')//处理最后一个字串
                p++;
            while(s<=p)
            {
                temp=*p;
                *p=*s;
                *s=temp;
                s++;
                p--;
            }//反转局部字符串

            s=q+1;
            p=q;
        }
        q++;
        p++;
    }

    printf(str);
    printf("\n");
}
第二种:

#include <iostram>
#include <stdio.h>

int main(void)
{
    int num=-12345,j=0,i=0,flag=0,begin,end;
    char str[]="I am a student",temp;
    j=strlen(str)-1;
    
    printf(" string=%s\n",str);
    //第一步是进行全盘反转,将单词变成“tneduts a ma I”
    while(j>i)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
        j--;
        i++;
    }
    printf(" string=%s\n",str);
    int i=0;
    //第二步进行部分反转,如果不是空格则开始反转单词
    while(str[i])
    {
        if(str[i]!=' ')
        {
            begin=i;
            while(str[i]&&str[i]!=' ')
            {
                i++;
            }
            i=i-1;
            end=i;
        }
        while(end>begin)
        {
            temp=str[begin];
            str[begin]=str[end];
            str[end]=temp;
            end--;
            begin++;
        }
        i++;
    }
    printf(" string=%s\n",str);
    return 0;
}
第三种:


void  ReverseWord( char * p,  char * q)
{
     while (p < q)
     {
         char  t = *p ;
         *p++ = *q ;
         *q-- = t ;
     }
}
 
char * ReverseSentence( char  *s)
{
     char  *p = s ;    // point to the first char of a word
     char  *q = s ;    // point to a white space or '\0'
 
     while (*q !=  '\0' )
     {
         if  (*q ==  ' ' )
         {
             ReverseWord(p, q - 1) ;
             q++ ;  // move to next word
             p = q ;
         }
         else
             q++ ;
     }
 
     ReverseWord(p, q - 1) ;  // Reverse the last word
     ReverseWord(s, q - 1) ;  // Reverse the whole sentence
 
     return  s ;
}

转载于:https://my.oschina.net/u/2564478/blog/667532

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值