这里给出题目链接(hdu1062)。
当我们看到题目给出的输入和输入实例的时候,应该已经明了了。
Sample Input
3
olleh !dlrow
m'I morf .udh
I ekil .mca
Sample Output
hello world!
I'm from hdu.
I like acm.
Hint
Remember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.
这是一道简单的字符串处理问题 。
首先,需要注意的是这里的Hint,我们需要在输入t后使用sc.nextLine()接收一个回车,否则会导致第一个数据输入出现问题。
其次,输入完一个数据后按回车开始输入下一个数据,即每一个数据占一行,那么这里需要按行接收数据。声明一个String类型的字符串str去存储每一行的数据。
然后,每一个数据需要把里面的单词逐个逆序,这里使用split()将数据按单词拆分开,我们再声明一个String类型的字符串数组strs去存储拆分后的数据,随后遍历strs,利用charAt()函数将每个单词逆序后存入String类型的output中,最后别忘了加上空格。
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while (t-- > 0)
{
String str = sc.nextLine();
String []strs = str.split(" ");
String output = "";
for (int i = 0; i < strs.length; i++)
{
for (int j = strs[i].length() - 1; j >= 0; j--)
output += strs[i].charAt(j);
if ((i + 1) == strs.length)
continue;
output += " ";
}
if (str.endsWith(" "))
output += " ";
System.out.println(output);
}
}
}