Home > Enterprise >  Capitalizing the last 2 letters in java
Capitalizing the last 2 letters in java

Time:01-25

Hi Im a beginer in java andd we were given a assignment to captilize the last 2 letter of any given word can someone help me do that?

I was able to figuire out how to captilize the the 1st and last letter but I have no clue how to cap the last 2 letters?

I also Have clue how to make it in a keyboard input and a have it cap the last 2 lettrs and give a output.

Ex- input eat output- eAT

class Main {
    static String FirstAndLast(String str)
    {
        // Create an equivalent char array of given string
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i  ) {

            // k stores index of first character and i is going to store index of last character.
            int k = i;
            while (i < ch.length && ch[i] != ' ')
                i  ;

            // Check if the character is a small letter If yes, then Capitalise
            ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z'
                               ? ((int)ch[k] - 32)
                               : (int)ch[k]);
            ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z'
                                   ? ((int)ch[i - 1] - 32)
                                   : (int)ch[i - 1]);
        }
        return new String(ch);
    }

    public static void main(String args[])
    {
        String str = "Prep insta";
        System.out.println("Input String:- " str);
        System.out.println("String after Capitalize the first and last character of each word in a string:- " FirstAndLast(str));
    }
}

CodePudding user response:

How about using a simpler approach

  1. Get a string

  2. Cut 2 last letters and remember them

  3. Capitalize them

  4. Join 2 parts together

    public static void main(String[] args) {
        String input="yourInputFromSomewhere";
        int cutPoint=input.length()-2;
        String fixed=input.substring(0,cutPoint);
        String toCapitalize=input.substring(cutPoint);
        System.out.println(fixed toCapitalize.toUpperCase());
    }
    

Output:

yourInputFromSomewheRE

CodePudding user response:

The easiest way to do this is probably to use the base string methods:

String input = "capitalize";
String output = input.substring(0, input.length() - 2)  
                input.substring(input.length() - 2).toUpperCase();
System.out.println(output);  // capitaliZE

CodePudding user response:

To capitalize the last 2 letters of a given word, you can use the substring method to extract the last 2 letters and then use the toUpperCase method to capitalize them. Here is an example of how you can modify your existing code to capitalize the last 2 letters:

if(str.length()>2) {
    String last2 = str.substring(str.length() - 2);
    last2 = last2.toUpperCase();
    str = str.substring(0, str.length() - 2)   last2;
}
  •  Tags:  
  • java
  • Related