1009. 说反话 (20)

1009. 说反话 (20)
注意fgets、gets、scanf函数读入字符串比较:
fgets(str, SIZE, stdin);
gets(str);
scanf(“%s”, str);

  fgets读入的是带’\n’的字符串。也就是说,在不超过第二个参数的情况下,fgets从第三个参数(文件指针,输入流)中不断的读入字符,直到遇到’\n’并将’\n’从输入流中取出
  gets函数不检测读入的字符的个数。仅仅是不断的从标准输入流(键盘)中读入字符,直到遇到’\n’。与fgets不同的是,虽然gets函数也会将’\n’从输入流中取出,但却只是取出,然后丢掉。并不保存在目标字符串中
  scanf函数不检测读入的字符的个数。仅仅是不断的从标准输入流(键盘)中读入字符,直到遇到“空白符”。和fgets/gets不同的是,scanf不从输入流中取出“空白符”。

/*  coded by indere 2017/06/20
    题目: 
    给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

    输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。
    字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,
    单词之间用1个空格分开,输入保证句子末尾没有多余的空格。

    输出格式:每个测试用例的输出占一行,输出倒序后的句子。

    输入样例:
    Hello World Here I Come
    输出样例:
    Come I Here World Hello
*/

/*  分析:
    首先分析字符串大小:最多80个字符,因为我是用fgets读取,所以还要包括一个'\n'和一个'\0',
    所以最大字符串数组长度最小设置为82。

    然后是翻转操作,
    1、创建新的字符串数组newstr,跳过'\n',从后往前读,读到' ',将单词用strcat()连接到newstr上

    2、然后把原始字符串数组str的‘\0’往前移,移到第一步查到的' '后面。

    3、重复步骤12,直到读到读到起始端。

    4、最后别忘了把最后一个字符由' '改为'\0'

    模拟步骤:
    例如:
    str = "Hello World Here I Come\n"
    str = "Hello World Here I Come "         // 把'\n' 改为‘ ’
    strcat(.....)                            // 连接
    newstr = "Come "
    str = "Hello World Here I "              //把'\0'前移

    strcat(.....)
    newstr = "Come I "
    str = "Hello World Here "                //把'\0'前移

    strcat(.....)
    newstr = "Come I Here "
    str = "Hello World "                    //把'\0'前移

    strcat(.....)
    newstr = "Come I Here World "
    str = "Hello "                          //把'\0'前移

    strcat(.....)
    newstr = "Come I Here World Hello "

    newstr = "Come I Here World Hello"      //最后把newstr的'\0'前移
*/

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

#define MAXSIZE 82
const int strsize = sizeof(char) * MAXSIZE;

char* reverseStr(char *str);                /*字符串翻转*/

int main() {
    char *str = (char *)malloc(strsize);
    memset(str, 0, strsize);
    fgets(str, MAXSIZE,stdin);
    str = reverseStr(str);
    printf("%s\n", str);
    return 0;
}

char* reverseStr(char *str) {
    char *newstr = (char *)malloc(strsize);
    memset(newstr, 0, strsize);
    int temp = strlen(str) - 1;
    for (int i = temp - 1; i >= 0; i--) {
        if (str[i] == ' ') {
            str[temp] = ' ';
            strcat(newstr, &str[i+1]);
            temp = i;
            str[temp + 1] = 0;
        }
    }

    strcat(newstr, str);
    newstr[strlen(newstr) - 1] = 0;
    return newstr;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值