Search code examples
javastringbuilder

I want to delete the last two letters form a verb and conjugate it using StringBuilder


Everything is explained in the comments

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"));

I got StringIndexOutOfBoundsException.

I can help more according to your questions.


Solution

  • 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");
    

    This uses a regular expression replaceFirst. The pattern:

    • . any character
    • . any character
    • $ end of string

    Hence: the last two letters are replaced by the empty string.

    The minor advantage over chaine.substring(0, chaine.length() - 2) is that for the empty string or one-letter string no indexing error happens; it does no replacing. Admittedly substring is faster.