0

I'm trying to make a method that shall help me to spell world right. After addChar have return its work based on the input "famili", I want the result array to contain the word "familiy". Now the method removes a character from the string and replace it with the current char in alpha[], can someone please give me some help to make this method to add the char from alpha[] between two characters and not delete one to get space.

class Main {
       char [] alpha = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                        'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'y', 'z'};
        public static void main(String [] args) {

            Main m = new Main();
            String [] result = m.addChar("famil");
        }

        public String[] addChar(String word) {

            String [] words = new String[word.length() * alpha.length];
            int k = 0;

            for(int i = 0; i < alpha.length; i++) {
                for(int j = 0; j < word.length(); j++) {
                    StringBuffer buf = new StringBuffer(word);
                    buf.setCharAt(j, alpha[i]);
                    words[k++] = buf.toString();
                }
            }
            return words;
        }
}

3 Answers 3

3

You can make use of the insert method of the StringBuffer class in place of setCharAt.

Working link

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

Comments

1

I would probably solve it like this.

for (int i = 0; i < alpha.length; i++)
    for (int j = 0; j < word.length(); j++)
        words[k++] = word.substring(0, j) + alpha[i] + word.substring(j);

Comments

0

Try to use LinkedList.

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.