
保姆级教程!!!!
先给代码 再来详细讲解
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();//控制输入的行数
int count = 0;//控制输出时的空格
String str = s.nextLine();//吸收't'
for (int i = 0;i < n; i++){
String s1 = s.nextLine();
String[] strings = s1.split(" ");//将字符串通过空格分隔成几个小字符串
for(int j = 0; j < strings.length; j++){
char[] chars = strings[j].toCharArray();//将字符串变成单个字符保存的数组中
char[] chars1 = new char[chars.length];
for(int k = 0; k < chars.length; k++){
chars1[k] = chars[chars.length-1-k];//反转
}
String s2 = String.valueOf(chars1);//将字符数组转换为字符串
if(count==1){//空格的输出
System.out.print(" ");
count = 0;
}
count = 1;
System.out.print(s2);
}
count = 0;
if(i
运行结果如图:
详细讲解:
先来读题,讲题目分解成几个小部分。
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.
输入
输入包含几个测试用例。输入的第一行是一个整数 T,它是测试用例的数量。T测试用例如下。 每个测试用例包含一行,其中包含多个单词。一行最多有1000 个字符。
Output
For each test case, you should output the text which is processed.
输出
对于每个测试用例,您应该输出处理的文本。
然后我们看看给出的案例:
大体思路
1.首先输入一个整数,这个整数的用于控制接下来输入几行。
2.输入一行字符串
3.将大字符串用空格分隔成几个小字符串(olleh !dlrow 分为 olleh 和 !dlrow 两部分)
4.将小字符串反转
5.输出
既然知道了大体的思路,我们就来一步一步的解决问题。
1.输入整数,用于控制输入的行
Scanner s = new Scanner(System.in);
int n = s.nextInt();
String str = s.nextLine();//吸收n后面的换行
for (int i = 0;i < n; i++){
……
……
}
注意这里有一个 int n = s.nextInt();
用于吸收输入 n 之后的那个 ‘t’ 。
2.输入一行字符串,按照空格将字符串分隔成几个小字符串。
String s1 = s.nextLine();
String[] strings = s1.split(" ");
对于split的使用方法,大家可以复制下面的代码到自己的电脑里运行,一运行就可以明白了。
public class Main {
public static void main(String[] args) {
String address = "江西@南昌";
String[] add = address.split("@");//这是String类中的一个方法,返回的只能是String类型。
//split 会自动根据@将分隔开的字符串保存到add这个字符串数组中。
System.out.println(add[0]+" "+add[1]);
}
}
运行结果:
3.将字符串反转
for(int j = 0; j < strings.length; j++){
char[] chars = strings[j].toCharArray();
……
……
}
要将字符串反转,首先需要将字符串中的每一个字符单独放到一个数组中。
这里的 j 表示第几个小字符串
strings.length 小字符串的总个数(对于olleh !dlrow来说是两个)
for(int k = 0; k < chars.length; k++){
chars1[k] = chars[chars.length-1-k];
}
通过一个for循环将字符数组反转。
这里的 k 表示小字符串的第几个字符。
chars.length 小字符串中共有几个字符(对于!dlrow来说是6个)
到这里大体的思路和步骤就完成了,接下来就是输出的格式了。
看到这里希望大家可以点赞、评论、收藏。谢谢大家!!!
如果还有什么不明白的地方可以问我哦!!!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)