Muldawg2020 Muldawg2020 - 7 months ago 25
Java Question

Check if a String has vowels, and create a new String that doubles the consonants

So here's what I'm trying to do. I take a given string, and make a new string. The new string will be the same as the original string, but will have the consonants doubled.

For example,

and so forth. It only doubles the consonants that aren't already doubled.

Here's what I have so far:

// Returns a new string in which all consonants in the given string are doubled.
// Consonants that are already doubled are not doubled again.
// For example, doubleConsonants("rabbit") returns "rrabbitt".
// It is assumed that in the given string is alphabetic and that no character
// appears more than twice in a row.
// Parameters:
// s - given string
// Returns new string with all consonants doubled
public static String doubleConsonants(String s) {

String newString = "";
String vowels = "aeiouAEIOU";

for (int i = 0; i < s.length(); i++) {

boolean hasVowel = false;
for (int n = 0; n == 10; n++){

if ( vowels.charAt(n) == s.charAt(i)) {

newString += s.charAt(i);
hasVowel = true;
if (hasVowel = false && s.charAt(i) != s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)) {

newString += s.charAt(i);
else if (hasVowel = false) {

newString += s.charAt(i);
return newString;

Apparently there are some issues with "dead code" and the boolean hasVowels is "not used". What am I screwing up?


Try this.

public static String doubleConsonants(String s) {
    return s.replaceAll("(?i)([^aeiou])\\1", "$1")
        .replaceAll("(?i)([^aeiou])", "$1$1");