编程之法(单词翻转)

    xiaoxiao2021-12-14  25

      题目:输入一个英文句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开(标点符号和普通字母一样处理)。如:输入“I am a student.” ,则输出

    “ student. a am I”.

    解法:(1)、由题目知,单词内的字符顺序不变,并以空格符隔开,则将单词与标点符号看着为整体,如A_B_C_D. 空格以下横线表示。(2)由上述得出,题目即为对A_B_C_D.进行反转,结果为D._C_B_A   ;(3)以空格符作为每个字符串的条件。

    代码如下:

    #include<iostream>

    #include<assert.h>

    using namespace std;

    void str_swap(char *a,char *b)   //交换字符串

    {

         assert(a!=NULL&&b!=NULL);               

         char temp=*a;

                   *a=*b;

                   *b=temp;

    }

    void str_reverse(char *from,char *to)   //交换指定区间[from,to]之间的字符串

    {

            while(from<to)

                     {    str_swap(from,to);

                           from++;

                           to--;                  }

    }

    void reverse(char *str)    //反转字符串函数

    {

            assert(str!=NULL); 

            char *from=str;         

            char *to=from;

            for( ;*to!='\0';to++);

            --to;

            str_reverse(from,to);

            from=str;

             to=from;

             char *word_to=NULL;

             do{

                        if(*to==' '||*to=='\0')

                           word_to=to-1;

                            str_reverse(from,word_to);

                            from=to;

                            while(*from==' ')

                                 {

                                   from++;

                                  }to++

                   }while(*(to-1)!='\0');

    }

    int main()

    {

            char str[]="I am a student.";

            cout<<str<<endl;

            reverse(str);

            cout<<str<<endl;

            return 0;

    }

    转载请注明原文地址: https://ju.6miu.com/read-970915.html

    最新回复(0)