[C++]PAT乙级1009. 说反话 (17/20)

时间:2023-03-09 23:45:06
[C++]PAT乙级1009. 说反话 (17/20)
/*
1009. 说反话 (20) 给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。 输入格式:
测试输入包含一个测试用例,
在一行内给出总长度不超过80的字符串。
字符串由若干单词和若干空格组成,
其中单词是由英文字母(大小写有区分)组成的字符串,
单词之间用1个空格分开,
输入保证句子末尾没有多余的空格。 输出格式:
每个测试用例的输出占一行,输出倒序后的句子。 输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
*/ /*
思路1:
0.创建单词临时缓冲区buffer[80],单词数组words[40][80],并初始化,单词计数器words_count=0;
1.输入字符串str;
2.遍历字符串str内字符元素str[i]
若str[i] != ' ': strcat(buffer, str[i]);
否则:strcpy(words[words_count++],buffer), tmp清空; 思路2:
对单词的位置标记下来,然后字符串逆序输出。(注意:对连续空格的位置要处理) 分析:
单词数[0, 40];
*/
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std; struct Words{
int wds_start;
int wds_len=0;
}; void print(char *chs, int start,int len){
for(int i=start,length = start+len;i<length;i++){
printf("%c", chs[i]);
}
}
// 1 6/7 10/11/12/13/14
// I am home.
int main(){
char str[80];
Words wds[80];//从下标1开始,sps[0]作为字符串第一个空格点
int words_count=0;//从下标1开始 //init
str[0] = '\0'; //input data
cin.getline(str, 80, '\n');//读取一行字符串,以'\n'作为结束标识符,最多读取80个字符 //printf("string's length:%d\n", strlen(str));//test for(int i=0;i<strlen(str);i++){
if(str[i] == ' '){//空格不处理 } else {//非空格
if(str[i-1] == ' ' || (i==0)){//单词开始,注意:需要对wds[0]位特殊考虑
// printf("[%d] char:%c\n", i, str[i]);//test
words_count++;
wds[words_count].wds_start = i;
}
wds[words_count].wds_len++;
}
} // test
// for(int i=1;i<=words_count;i++){
// printf("words(%d):{start:%d;len:%d}\n", i, wds[i].wds_start, wds[i].wds_len);
// } for(int i=words_count;i>0;i--){
print(str, wds[i].wds_start,wds[i].wds_len);
printf("%s", i==1?"":" ");//最后一个单词不需要空格
}
//printf("*");
return 0;
} /*
参考:https://www.jianshu.com/p/ea251483355c
//C/C++实现 20/20
//思路:从后到前,依次遍历,当找到单词首字符的前的第一个空格时,输出其后的单词,同时将输出的字符以str[i]='\0'截断
#include <stdio.h>
#include <iostream>
#include <string.h> using namespace std; int main(){
char c[82];
gets(c+1);
c[0] = ' ';
for(int i=strlen(c);i>=0;i--){
if(c[i] == ' '){
printf("%s", c+i+1);
c[i] = '\0';
if(i == 0){
printf("%c", '\n');
}
else{
printf("%c", ' ');
}
}
else{
continue;
}
}
return 0;
}
*/