Home > Back-end >  Hello I am trying to write a method that duplicates all vowels but only if they are on their own. fo
Hello I am trying to write a method that duplicates all vowels but only if they are on their own. fo

Time:10-13

Here's what I have if someone could give me some idea of what to do that would be great. I think taking the index and counting how many values are together would be helpful but im not sure how to implement that. isVowel is a helper method to determine if the char is a vowel.

public static String doubleVowelsMaybe(String s) 
{  
    int run =0;
    String n = "";
    for(int i = 0; i< s.length();   i)
    {
        char k = s.charAt(i);
        if(isVowel(k))
        {
            
        }
        if(run == 1)
        {
            n = n   s.substring(i, i 1)   s.substring(i, i 1);
            run=0;
        }
        else
        {
            n = n   s.substring(i, i 1);
            run= 0;
        }
    }
    
    return n;

CodePudding user response:

Most simple string manipulation tasks like this can be fairly easily done with a regex. This one's a one-liner:

public static String doubleVowelsMaybe(String s) {
    return s.replaceAll("(?<![aeiou])([aeiou])(?![aeiou])", "$1$1");
}

The regex works as follows:

  • (?<![aeiou]) is a negative lookbehind, so it matches only if the character is not preceded by a vowel.
  • ([aeiou]) matches a single vowel, and captures it to group number 1.
  • (?![aeiou]) is a negative lookahead, so it matches only if the character is not followed by a vowel.
  • The replacement of $1$1 means two copies of whatever was matched by group number 1, which is the single vowel character.

CodePudding user response:

import java.util.*;

class Hello {
    public static void main(String[] args) {
        String abc = "beautiful";
        String n = "";
        int i = 0;
        char[] abcchar = abc.toCharArray();
        HashSet<Character> hs = new HashSet<>();
        hs.add('a');
        hs.add('e');
        hs.add('i');
        hs.add('o');
        hs.add('u');
        while (i < abcchar.length) {
            if (i   1 < abcchar.length && hs.contains(abcchar[i]) && !hs.contains(abcchar[i   1])) {
                n = n   abc.substring(i, i   1)   abc.substring(i, i   1);
            } else {

                while (hs.contains(abcchar[i])) {
                    n = n   abc.substring(i, i   1);
                    i  ;
                }
                n = n   abc.substring(i, i   1);
            }
            i  ;
        }
        System.out.print(n);
    }
}
  •  Tags:  
  • java
  • Related