题目:
从控制台接收用户输入的一行英文句子,把句子的最前面两个单词移到句子的最后面去,并整理句子的大小写及标点符号,将新的句子输出。
input: The dog ran through the gate and down the street.
output: Ran through the gate and down the street, the dog?
input: My coat was too heavy for this warm day!
output: Was too heavy for this warm day, my coat?
代码如下:
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
// 接受字符串并转化为字符串数组
System.out.print("input:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
sc.close();
String[] arr = str.split(" ");
// 改变顺序(通过创建新数组)
String[] newStr = new String[arr.length];
int i;
for (i = 0; i < newStr.length - 2; i++) {
newStr[i] = arr[i + 2];
}
newStr[i] = arr[0];
newStr[i + 1] = arr[1];
// 改变大小写
String temp1 = "";
char c1 = newStr[0].charAt(0);
c1 = (char) (c1 - 32);
temp1 += c1;
temp1 += newStr[0].substring(1);
newStr[0] = temp1;
String temp2 = "";
char c2 = newStr[i].charAt(0);
c2 = (char) (c2 + 32);
temp2 += c2;
temp2 += newStr[i].substring(1);
newStr[i] = temp2;
// 改变标点符号
String temp3 = "";
temp3 += newStr[i - 1].substring(0, newStr[i - 1].length() - 1);
temp3 += ',';
newStr[i - 1] = temp3;
newStr[i + 1] += "?";
// 输出
System.out.print("output:");
for (int j = 0; j < newStr.length; j++) {
System.out.print(newStr[j] + " ");
}
}
}