7-6 单词反转
对于一行英文句子,在输出时将每个单词倒过来,但不改变单词的顺序。
输入格式:
第一行是一个整数n,表示英文句子的个数。接下来的n行是n条句子,每个句子的长度不超过1000,且其中不包含标点。
输出格式:
按要求在每行上输出单词反转处理后的句子。
输入样例:
3
I am happy today
To be or not to be
I want to win the practice contest
输出样例:
I ma yppah yadot
oT eb ro ton ot eb
I tnaw ot niw eht ecitcarp tsetnoc
本题难点:
1、由于和以往的提不太一样,以往的说反话仅是将句子的顺序颠倒即可,而本题需要在颠倒单词的同时句子顺序不变
2、在输入时需要读取空白,不能用" cin >> “或者” scanf() "
录入空白
选择使用cin的getline()方法读取输入的句子
cin.getline()相关介绍:
https://www.cnblogs.com/shaguargeffon/p/14966529.html
注意:在cin.getline() 使用前如果使用了" cin >> ",cin.getline就会在首行多读取到一行空白,原因是cin的缓冲区未清除,在键入值后的回车就会被cin.getline()读取为第一行。这种情况需要在cin.getline()使用前用cin.ignore()方法清除cin的缓冲区
cin.ignore()相关介绍:
https://blog.csdn.net/wxbmelisky/article/details/48596881
输入:
int group;
cin >> group ;
cin.ignore();
char sentence[100][1000] = { '\0' };
for (int i=0;i<group;i++)
{
cin.getline(sentence[i], 1000);
}
读取到内容后需要进行单词的颠倒处理,我们可以去逐行处理,在每一行中逐字符判断,若遇到空白,则将空白前的单词进行颠倒,由于行末没有空白,需要加上行末判断标志
颠倒处理:
for (int i = 0; i < group; i++)
{
int start = 0;
for (int j = 0; j < strlen(sentence[i]); j++)
{
if (sentence[i][j] == ' ')
{
int end = j - 1;
for (int s = start, e = end; s < e; s++, e--)
{
char temp = sentence[i][s];
sentence[i][s] = sentence[i][e];
sentence[i][e] = temp;
}
start = j + 1;
}
if (j == strlen(sentence[i]) - 1)
{
int end = j;
for (int s = start, e = end; s < e; s++, e--)
{
char temp = sentence[i][s];
sentence[i][s] = sentence[i][e];
sentence[i][e] = temp;
}
}
}
}
参考代码:
#include<iostream>
#include<cstring>
using namespace std;
void exchange()
{
int group;
cin >> group ;
cin.ignore();
char sentence[100][1000] = { '\0' };
for (int i=0;i<group;i++)
{
cin.getline(sentence[i], 1000);
}
for (int i = 0; i < group; i++)
{
int start = 0;
for (int j = 0; j < strlen(sentence[i]); j++)
{
if (sentence[i][j] == ' ')
{
int end = j - 1;
for (int s = start, e = end; s < e; s++, e--)
{
char temp = sentence[i][s];
sentence[i][s] = sentence[i][e];
sentence[i][e] = temp;
}
start = j + 1;
}
if (j == strlen(sentence[i]) - 1)
{
int end = j;
for (int s = start, e = end; s < e; s++, e--)
{
char temp = sentence[i][s];
sentence[i][s] = sentence[i][e];
sentence[i][e] = temp;
}
}
}
}
for (int i = 0; i < group; i++)
{
cout << sentence[i] << endl;
}
}
int main()
{
exchange();
return 0;
}
欢迎交流学习
原创不易,看官点个赞再走~~~