算法3——字符串反转

Problem Description

Lgnatius likes to write words in reverse way.Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.

Output

For each test case, you should output the text which is processed.

Sample Input

3

olleh       !dlrow

m’I   morf  .udh

I      like      .mca

Sample Output

hello   world!

I’m     from    hdu.

I        like     acm.

字符串反转源码(C语言)

#include <stdio.h>
#include <string.h>
int main()
{
    int n,i,j,flag;
    /*scanf返回成功读取的个数,或者EOF,EOF=-1
    负数的取反操作等于正数取反加1再取反
    -1 -> 0001 -> 1110 + 1 -> 1111 -> 0000*/
    while (~scanf("%d", &n))   /*scanf读取n后,会留下一个\n在缓冲区,通过getchar进行消化,不然下面的gets函数会读取\n*/
	{
        getchar();
        while (n--) {
            char s[1010] = "";
            gets(s);
            flag = 0;
            /*从0开始处理字符串*/
            for (i = 0; i < (int)strlen(s); ++i) {
                /*碰到空格*/
                if (s[i] == ' ') {
                    /*倒着开始读取每一个字符*/
                    for (j = i - 1; j >= flag; j--) {
                        printf("%c", s[j]);
                    }
                    printf(" ");
                    flag = i + 1; //标记位置
                }
            }
            /*上面i已经遍历到了最后,直接倒着读取字符输出*/
            for (j = i - 1; j >= flag; j--) {
                printf("%c", s[j]);
            }
            printf("\n");
        }
    }
    return 0;
}

算法要求已达到,可根据实际需求然后使用数组将其储存起来放在后面一起输出,不过意义不大。

/*本篇文章转载自微信公众号ACM算法日常*/

 

点赞