Home > Net >  Replace last two letters in Java
Replace last two letters in Java

Time:05-02

I am asking for help on this code that I am making, I want it to replace the last two letters. I am coding a program that will:

  1. Replace four letter words with "FRED"
  2. Replace the last two letters of a word that ends with "ed" to "id"
  3. Finally, replace the first two letters if the word starts with "di" to "id"

I am having difficulty with the second stated rule, I know that for number 3 I can just use replaceFirst() and to use the length for the first rule, but I am not sure how to specifically swap the last two characters in the string.

Here is what I have so far:

package KingFred;

import java.util.Scanner;

public class KingFredofId2 {

public static void main(String args[])
{
    Scanner input = new Scanner(System.in);
    String king = input.nextLine();
    String king22 = new String();
    String king23 = new String();
    if(king.length()==4)
    {
        System.out.println("FRED");
    }
    String myString = king.substring(Math.max(king.length() - 2, 0));
    if (myString.equals("ed")) 
    {
        king22 = king.replace("ed", "id");
        System.out.println(king22);
    }
    if(true)
    {
        king23 = king.replace("di", "id");
        System.out.println(king23);
    }
}

I am new to Stack Overflow, so please let me know how I can make my questions a little more understandable if this one is not easily comprehended.

Thanks.

CodePudding user response:

This is the most simplest way I could think to solve the second case of replacing the last two characters.

import java.util.Scanner;

public class MyClass {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a line or a word: ");
        String s = sc.nextLine();

        //getting the length of entered string
        int length = s.length();
        
        //initializing a new string to hold the last two characters of the entered string
        String extract = "";

        //checking if length of entered string is more than 2
        if (length > 2) {
            //extracting the last two letters
            extract = s.substring(length - 2);
            //updating the original string
            s = s.substring(0, length - 2);
        }


        //checking if the last two characters fulfil the condition for changing them
        if (extract.equalsIgnoreCase("ed")) {
            //if they do, concatenate "id" to the now updated original string
            System.out.println(s   "id");
        } else {
            //or print the originally entered string
            System.out.println(s   extract);
        }
    }
}

I believe the comments are giving enough explanation and further explanation is not needed.

  • Related