Java 如何删除字符串的最后两个字母?

Java 如何删除字符串的最后两个字母?,java,Java,问题: 提示用户输入一个字符串,并检查它是否是以“s”或“es”结尾的复数形式。输出单词的单数形式。如果用户输入一个单数单词,只需输出该单词即可 例如: 输入以s或es结尾的复数单词: 房屋 单词的单数版本:House 我该如何打印出没有字母的单词 以下是我迄今为止所尝试的: System.out.println("Input a plural word: "); String pluralWord = kb.nextLine(); if (pluralWord.substring(plural

问题:

提示用户输入一个字符串,并检查它是否是以“s”或“es”结尾的复数形式。输出单词的单数形式。如果用户输入一个单数单词,只需输出该单词即可

例如:

输入以s或es结尾的复数单词: 房屋 单词的单数版本:House 我该如何打印出没有字母的单词

以下是我迄今为止所尝试的:

System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();
if (pluralWord.substring(pluralWord.length()-2).equals("es") || pluralWord.substring(pluralWord.length()-2).equals("s"))
    System.out.println("Singular version of the word:"+ );
您可以使用printf。还有,然后是和/或子字符串0,类似len-1


查看字符串的API。您正在寻找可以在字符串中提供子字符串位置的方法,可能从字符串的末尾开始,以便提取子字符串。另外看看endsWith,我认为它在这里更合适。我知道如何使用.endsWith,但是如何打印出这个单词呢?您想创建一个新的单数字符串,它是复数的子字符串。嗯,那是一种方式。API是一本非常开放的书。阅读方法说明,你会有一些想法。houses word只是一个例子吗,如果你想解析复数结尾,你需要一本字典,否则你会遇到问题。Flies->fly在本例中,单数形式不是fli@HyunseokSong,请记住,有很多英文单词是不适用的:刀、老鼠、鹅、仙人掌、人、脚、鱼等等。不,我不想打印最后两个字母。如果子字符串包含多个参数,我希望打印出第一个字母。如果只有@hyunseksong忘记了substring方法的第一个参数;
System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();

if(pluralWord.substring(pluralWord.length()-2).equals("es")){
   System.out.println("Singular version of the word:"+ pluralWord.substring(0, pluralWord.length()-2));
}else if(pluralWord.substring(pluralWord.length()-1).equals("s")){
   System.out.println("Singular version of the word:"+ pluralWord.substring(0, pluralWord.length()-1));
}else{
   System.out.println("Singular version of the word:"+ pluralWord);
}
public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.println("Input a word: ");
    String pluralWord = kb.nextLine();
    if (pluralWord.endsWith("es")) {
        System.out.printf("Plural %s, Singular %s%n", pluralWord,
                pluralWord.substring(0, pluralWord.length() - 2));
    } else if (pluralWord.endsWith("s")) {
        System.out.printf("Plural %s, Singular %s%n", pluralWord,
                pluralWord.substring(0, pluralWord.length() - 1));
    } else {
        System.out.printf("Singular %s%n", pluralWord);         
    }
}
System.out.println("Input a plural word: ");
String pluralWord = kb.nextLine();


if(pluralWord.length() > 1 && plurpluralWord.substring(pluralWord.length()- 2).equals("es") {
        System.out.println("Singular version of the word:"+
         pluralWord.substring(0 , pluralWord.length()-2));
}else if (pluralWord.length() > 0  && pluralWord.substring(pluralWord.length()- 1).equals("s")){
      System.out.println("Singular version of the word:"+ pluralWord.substring(0 , pluralWord.length()-1));
}else{
      System.out.println("Singular version of the word:"+ pluralWord);
}