1

I am currently creating a program that takes a string variable into my method, that string variable is copied into a new string variable which I have created. It then takes my new string variable and checks for any vowels in my String. It then takes the vowels and doubles them with my replaceAll() method. I am currently stuck on figuring out how to triple the non-vowels. So, for instance, the output for "easy!!" should be "eeaasssyyy!!!!!!.

I am looking for a simple way to do this -- any suggestions? I am a newbie to programming and Strings have me stumped.

public class RepeactChars
{
   public static void main(String[] args)
   {
      System.out.println(repeatChars("easy!!"));
      System.out.println(repeatChars("abc"));
      System.out.println(repeatChars("apple"));
      System.out.println(repeatChars("Homework"));
      System.out.println(repeatChars("Spring"));
      System.out.println(repeatChars("Integer"));
   }

   public static String repeatChars(String x)
   {
      String str = x;
      str = str.replaceAll("a", "aa");
      str = str.replaceAll("e", "ee");
      str = str.replaceAll("i", "ii");
      str = str.replaceAll("o", "oo");
      str = str.replaceAll("u", "uu");

      return str;
   }
}
0

3 Answers 3

3

I would use two regular expressions; in reverse order one to triple the consonants (everything not aeiou), and one to double the vowels (aeiou). Like,

public static String repeatChars(String x) {
    return x.replaceAll("([aeiou])", "$1$1").replaceAll("([^aeiou])", "$1$1$1");
}

And I get

eeaasssyyy!!!!!!
aabbbccc
aapppppplllee
HHHoommmeewwwoorrrkkk
SSSppprrriinnnggg
IIInnnttteegggeerrr

For the sake of completeness, you could also implement it with a StringBuilder and this is one place where the existence of switch case makes for an elegant solution (at least in my opinion). For example,

public static String repeatChars(String x) {
    StringBuilder sb = new StringBuilder();
    for (char ch : x.toCharArray()) {
        switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            sb.append(ch).append(ch);
            break;
        default:
            sb.append(ch).append(ch).append(ch);
            break;
        }
    }
    return sb.toString();
}

Outputs the same.

Sign up to request clarification or add additional context in comments.

5 Comments

@Elliot Frisch I like the regex solution you used, could you explain that solution a little more for me. Also the uppercase vowels I am noticing are appearing three times instead of two.
@hotrod28 What part needs more explanation? ([aeiou]) creates a group around vowels. "$1$1" says take any match from that group, and output it twice. The second replaceAll does the same, only starts with anything NOT matching a vowel and then triplicating it "$1$1$1".
Add AEIOU to both patterns to handle upper case. Your code only did lowercase, so I assumed that's all you cared about.
@ElliottFrisch Thanks for the quick replies I am looking through java docs and can't find why you used $1$1$1 could you explain what those special characters actually mean? I figured using the statement like your ([aeiou]){3} would work but it doesn't.
Reflex capturing group. () creates a group. The first group is $1. Your syntax says match three vowels.
0

Your method isn't particularly efficient, because each replaceAll call goes through the entire string.

The basic method is to loop through the string and for each character ask "is it a vowel." If it is, double it, else triple it.

You should really use the StringBuilder class, but I won't in this example.

public static String repeatChars(String x)
{
    String newStr = "";
    for (int i = 0; i < x.length(); ++i) {
       char c = x.charAt(i);
       int repeatTimes = "aeiou".indexOf(x.charAt(i)) == -1 ? 3 : 2;
       for (int j = 0; j < repeatTimes; ++j) {
           newStr += c;
       }
    }

  return newStr;
}

It's a bit wordy, but it's more efficient than using regex.

2 Comments

Readability and brevity are often more desirable than infinitesimal increases in efficiency in non-performance-critical code. Nice alternative to the regex approach though! If you're optimizing for performance, be careful of string concatenation in a loop like that. Java's instantiating (and then discarding) a StringBuilder instance for that under the hood each time. Instead of using string concatenation, declare your own StringBuilder instance outside the loop and append to that.
@nbrooks Agreed.
0

The innate problem with your solution is that you have to list every single char you want to use. The way to solve this is to loop through every char and generate a new string:

static String change(String in){
    String out = "";
    for(int i = 0; i < in.length(); i++){
        char letter = in.charAt(i);
        out += repeat(isVowel(letter)?3:2, letter);
    }
    return out;
}
static boolean isVowel(char c){
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public static String repeat(int count, char with) {
    return new String(new char[count]).replace("\0", ""+with);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.