Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        去年关闭。
                    
                
        

一切都在评论中解释

Scanner sc=new Scanner(System.in);

//asking for the verb
System.out.println("Donnez un verbe regulier du premier groupe :");

//putting the verb in the string
String chaine=sc.nextLine();

//taking the two last elements
char first=chaine.charAt(chaine.length());
char second=chaine.charAt(chaine.length()-1);

//creating a StringBuilder:
StringBuilder sb=new StringBuilder();

//putting string in the builder :
sb.append(chaine);

//deleting the two last characters :
sb.deleteCharAt(sb.length()-1);


//printing elemnts :
System.out.println("Je "+sb.append("e"));
System.out.println("Tu "+sb.append("es"));
System.out.println("Il/Elle "+sb.append("e"));
System.out.println("nous "+sb.append("ons"));
System.out.println("vous "+sb.append("ez"));
System.out.println("Ils/Elles "+sb.append("ent"));


我得到了StringIndexOutOfBoundsException

根据您的问题,我可以提供更多帮助。

最佳答案

String radical = chaine.replaceFirst("..$", "");

System.out.println("Je " + radical + "e");
System.out.println("Tu " + radical + "es");
System.out.println("Il/Elle " + radical + "e");
System.out.println("Nous " + radical + "ons");
System.out.println("Vous " + radical + "ez");
System.out.println("Ils/Elles " + radical + "ent");


这使用正则表达式replaceFirst。模式:


.任何字符
.任何字符
$字符串结尾


因此:最后两个字母被空字符串替换。

相对于chaine.substring(0, chaine.length() - 2)的次要优势
对于空字符串或一个字母的字符串,不会发生索引错误;
它没有替代。公认substring更快。

09-10 07:36