input:-
1
Ans kot
Output:-
kot Ans
INPUT: 输入的第一行包含测试用例的数量。每个测试用例由一行包含字符串组成。
输出 输出带有如上所述交换的字符串。**
代码: -
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.next();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
我的代码有什么问题?以上是我正在尝试的代码。
答案 0 :(得分:2)
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
你的代码片段只会“逐字逐句”而不是“逐个字符”地反转句子。因此,在将其追加到my[j]
StringBuffer
)
答案 1 :(得分:1)
使用此
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.nextLine();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.nextLine();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
答案 2 :(得分:0)
接受String
输入并以每个字符的相反顺序返回String
。
String reverse(String x) {
int i = x.length() - 1;
StringBuilder y = new StringBuilder();
while (i >= 0) {
y.append(x.charAt(i));
i--;
}
return y.toString();
}
答案 3 :(得分:0)
public static String reverseWords(String input) {
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
答案 4 :(得分:0)
您可以运行此代码:
String[] splitted = yourString.split(" ");
for (int i = splitted.length-1; i>=0; i--){
System.out.println(splitted[i]);
}
答案 5 :(得分:0)
多件事:
您正在使用next
api,它只会读取您逐字输入的字符串,然后循环直到您的示例中只有一次。所以请使用nextLine
api,它将读取整行而不是单词,然后按空格分割:
String b = sc.nextLine();
您正在使用nextInt
api读取输入,然后输入,当您使用next
api读取下一个令牌时,您有时可能会返回返回字符。而是使用:
int a = Integer.parseInt(sc.nextLine());
答案 6 :(得分:0)
Code:-
Scanner sc =new Scanner(System.in);
int a =Integer.parseInt(sc.nextLine());
StringBuffer result= new StringBuffer();
for (int i = 0; i <a; i++) {
String b=sc.nextLine();
String my[]= b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length-1; j >0; j--) {
r.append(my[j]+" ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
enter code here