'How can I trim the last letter of a String while looping (until what's left is a single letter)?

I'm creating a program that will count the number of letters, vowels and consonants from what user put into using Scanner. Here's my code: '''

static String phrase;
static int vowel = 0;
static int consonant = 0;
static String reverse = "";

public static void countChar() {
    System.out.println("\nNumber of characters: " + phrase.length());
}

public static void countVowelCons() {
    phrase = phrase.toLowerCase();

    for (int i = 0; i < phrase.length(); i++) {
        if (phrase.charAt(i) == 'a' || phrase.charAt(i) == 'e' || phrase.charAt(i) == 'i' || phrase.charAt(i) == 'o'
                || phrase.charAt(i) == 'u') {
            vowel++;
        } else if (phrase.charAt(i) >= 'a' && phrase.charAt(i) <= 'z') {
            consonant++;
        }
    }
    System.out.println("Number of vowels: " + vowel);
    System.out.println("Number of consonants: " + consonant);
}

public static void reverseString() {

    for (int i = phrase.length() - 1; i >= 0; i--) {
        reverse += phrase.charAt(i);
    }
    System.out.println(reverse);
}

'''

In the reverseString() method, how can I make the reversed String get trimmed or make the last letter deleted in a loop until all what's left is a single letter.

For example: User inputs "qwertyuiop".

What should be the output is something like this:

  • poiuytrewq poiuytrew poiuytre poiuytr poiuyt poiuy poiu poi po p

How can I make it done like that? Please help thanks alot!

''' public static void reverseString() {

    for (int i = phrase.length() - 1; i >= 0; i--) {
        reverse += phrase.charAt(i);
    }
    System.out.println(reverse);

'''



Solution 1:[1]

public static void reverseString() {
 StringBuilder reverseStr = new StringBuilder();
    for (int i = phrase.length() - 1; i >= 0; i--) {
        reverseStr.append(phrase.charAt(i));
    }
 reverse = reverseStr.toString();
    System.out.println(reverse);
}

//    OR You can use inbuild method reverse() of StringBuilder 

public static void reverseString() {
    StringBuilder reverseStr = new StringBuilder(phrase);
    reverse = reverseStr.reverse().toString();
    System.out.println(reverse);
}

Solution 2:[2]

Sometimes rather than fixing code, you find an easier way:

vowel = phrase.replaceAll("(?i)[^aeiou]", "").length();
consonant = phrase.replaceAll("(?i)[^b-z&&[^eiou]]", "").length();
reverse = new StringBuilder(phrase).reverse().toString();

See live demo.

The character counts work by replacing with blank (ie "deleting") characters that aren't the type being counted and using the length of the resulting string.

Reversing uses functionality provided by the StringBuilder built-in class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nirbhay
Solution 2