C语言实现-HDOJ-1062.Text Reverse

/*Problem Description
Ignatius 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 ekil .mca

Sample Output
hello world!
I’m from hdu.
I like acm.
*/
解题思路:

根据提示,需要用getchar()函数吃掉输入缓冲区中的‘ \n’
该题有多种解法(仅提供两种思路作为参考,解法2提供代码):

  1. 可以直接逐个判断字符串中的字符,然后根据情况分类输出
    2.可以把字符串存储进字符数组中,遍历字符数组,根据情况把字符复制到另一个字符数组;最后一起输出多个字符串

解题代码

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

int main()
{
    int T;
    scanf("%d", &T);
    getchar();  //需要注意吃掉缓冲区中的换行符

    char A[1010][1010];
    int i, j, k, len, sign, count;

    for (i = 0; i < T; i++)
    {

        char S[1000];
        gets(S);
        len = strlen(S);//求出该字符串的长度
        A[i][len] = '\0';

        j = 0;
        count = 0;
        while (j < len)
        {
            if (S[j] == ' ')    //如果该位置的字符是空格,那么就把前面统计的长度的字符串进行调换
            {
                A[i][j] = S[j]; //空格 直接 赋值给 A字符串中相同位置的字符
                for (k = j-count, sign = 0; k < j; k++,sign++)//子字符串调换顺序
                {
                    A[i][k] = S[j-1-sign];//BUG在此,需要特别注意哪个位置赋值给哪个位置
                }
                count = 0;//初始化子字符串的字符个数为零
            }
            else if (j == len-1)    //如果该位置的字符是结尾符,那么就只需要调换子字符串的字符
            {
                for (k = j-count, sign = 0; k <= j; k++,sign++)
                {
                    A[i][k] = S[j-sign];
                }
                count = 0;//此处初始化是为了防止影响输入的下一个字符串的遍历
            }
            else
            {
                count++;//如果既不是空格也不是结尾符,那么子字符串的字符个数自增
            }

            j++;
        }
    }

    //统一输出字符串
    for (i = 0; i < T; i++)
    {
        printf("%s\n", A[i]);
    }

    return 0;
}

如果有问题可以留言交流,我一定及时回复;
如果采纳麻烦您记得点个赞,我在集赞哈哈哈;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值