所以,我有这段代码。它打算采用一个句子,并在自己的行上打印每个单词。它也应该找到一个句子的十个中间字符。
我的问题是我不确定如何制作它以便我实际上得到一个句子的十个中间字符。目前在代码中,编写它以便找到最后两位数字。另外,我想这样做,而不是只在每一行打印出单词,我想说 “第一个字:这个”“第二个字:是”等等。不过,每个人都在一个单独的行上。非常感谢任何帮助或指导,谢谢!
import java.util.Scanner;
public class Sentence {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence with 5+ words: ");
String sentence = in.nextLine();
System.out.println();
int space = sentence.indexOf(" ");
sentence = sentence.substring(0, space) + "\n" + sentence.substring(space + 1);
System.out.println(sentence.replaceAll("\\s+", "\n"));
String substring = sentence.length() > 10 ? sentence.substring(sentence.length() / 2) : sentence;
System.out.println();
System.out.println("MIDDLE 10 CHARACTERS: " + substring);
}
}
答案 0 :(得分:0)
试试这个:
String sentence = "He went to Accra today";
while((sentence.length() < 10) || (sentence.length() > 10)){
sentence = sentence.substring(1);
sentence = sentence.substring(0,sentence.length()-1);
}
System.out.println("Middle 10 is \""+sentence+"\"");
输出:
中间10是“到阿克拉”