Search code examples
javastringstringbuffer

Java String Buffer - how to delete


I need to create a method which takes in a String and produces a new word which does not include vowels and replaces each consonant with its position in the original word. The word I am using is "program" so I should get back "12o457".

Below is my code - I am getting an out of bounds when I try to use the deleteCharAt but I can use append here fine.

public class Methods {

    public String getWord(String word){
        StringBuffer sb = new StringBuffer();


        for(int i=0; i<word.length(); i++)
        {
            if(word.charAt(i) =='a' ||
                word.charAt(i) == 'e' ||
                word.charAt(i) == 'i')
                {
                sb.deleteCharAt(i);
                }
        else if(word.charAt(i)=='o' || word.charAt(i)=='u')
            {
            sb.append(word.charAt(i));
            }
        else{sb.append((i));}
        }

        return sb.toString();

    }
}

Solution

  • You were trying to delete a char you never had on your StringBuilder, you just need to change your method as follows:

    public String getWord(String word) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == 'o' || word.charAt(i) == 'u') {
                sb.append(word.charAt(i));
            } else if (word.charAt(i) != 'a' && word.charAt(i) != 'e' && word.charAt(i) != 'i') {
                sb.append((i + 1));
            }
        }
        return sb.toString();
    }
    

    This way you only add the letters you want for example o and u and skip a, e, i vowels and all consonants. Also, indexes in Java start from 0 so, to get your desired ouput, you needed to append i + 1 instead of just i.

    After running the above code I get:

    12o457
    

    as expected. However you should rephrase your question because you don't want any vowel and you're adding o and u which are vowels. And you want the original position, so it's not i + 1 but i and it would give you:

    01o346
    

    However with a larger word this could give something like the following:

    Input: programprogram
    Output: 12o45789o111214
    

    As you can see it becomes messy. Hopefully you won't use a word with a length > 10 chars.

    Edit

    Also I hadn't noticed this but as @PeterLawrey said in his comment above, don't use String Buffer instead use a String Builder. For more information about this, see StringBuilder vs StringBuffer