word reverse order - flip

1. Problem description

    In an English sentence, eg:I love China. Reverse it according to the word order, it becomes China love I.

2. Problem-solving ideas

    N-step reversal:

    step1: First, a space is split, and the string is divided into k parts (the principle of taking spaces backwards);

    step2: Invert the substrings of the k parts respectively

    step3: Finally, reverse the whole string

3. Algorithm code

/***********************
Author:tmw
date:2018-3-17
***********************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define swap(x,y,t) (t=x,x=y,y=t)

void reverseString( char* str, int front, int end )
{
    char temp;
    while( front<end )
    {
        swap(str[front],str[end],temp);
        front++;end--;
    }
}

void three_steps_reverse( char* str )
{
    int i = 0;
    int j = 0;
    int mark_left,mark_right;
    while( i<strlen(str) )
    {
        while( i<strlen(str)&&str[i]!=' ' )
            i++;

        /**i now points to the space, where the coordinates are moved back**/
        i--;

        /**Protect the cursors of i and j from being changed**/
        mark_left = j;
        mark_right = i;

        reverseString(str,mark_left,mark_right);
        printf("%s\n",str);
        j = i + 2; //j points to the beginning of the next word
        i = j;
    }
    /**Final overall flip**/
    reverseString(str,0,strlen(str)-1);
}

4. Test code and results

intmain()
{
    printf("Test code\n");

    char str[] = "I love China.";
    printf("Before flip: %s\n",str);
    three_steps_reverse( str );
    printf("After flip: %s\n",str);

    return 0;
}

There is still a dream, if it comes true~~~ヾ(◍°∇°◍)ノ゙~~~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325909605&siteId=291194637