Muldawg2020 Muldawg2020 - 1 year ago 58
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?

Answer Source

Try this.

public static String doubleConsonants(String s) {
    return s.replaceAll("(?i)([^aeiou])\\1", "$1")
        .replaceAll("(?i)([^aeiou])", "$1$1");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download